首页 > 代码库 > Android--动态添加控件

Android--动态添加控件

 
 
 
 
[html]  
  
[html]  
package com.mrzhu.edittest;  
  
import android.app.Activity;  
import android.os.Bundle;  
import android.view.ViewGroup;  
import android.widget.RelativeLayout;  
  
public class EditTestActivity extends Activity {  
    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        //自定义的带提示文本的EditText组件  
        EditTextTest ed = new EditTextTest(this);  
        //设置从左边140px处开始输入文本  
        ed.setPadding(140, 0, 0, 0);  
        //装载一个布局文件,向这个布局中动态添加一个EditText  
        RelativeLayout relativeLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.main, null);  
        //创建一个LayoutParams对象  
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);  
        //设置android:layout_below属性的值   
        layoutParams.addRule(RelativeLayout.BELOW, R.id.button2);  
        //动态添加EditText  
        relativeLayout.addView(ed, layoutParams);  
        //设置布局  
        setContentView(relativeLayout);  
    }  
}  
 
自定义的EditText控件:
[html]  www.2cto.com
package com.mrzhu.edittest;  
  
import android.content.Context;  
import android.graphics.Canvas;  
import android.graphics.Color;  
import android.graphics.Paint;  
import android.util.AttributeSet;  
import android.widget.EditText;  
  
public class EditTextTest extends EditText {  
  
    public EditTextTest(Context context) {  
        super(context);  
    }  
      
    public EditTextTest(Context context, AttributeSet attrs, int defStyle) {  
        super(context, attrs, defStyle);  
    }  
  
    public EditTextTest(Context context, AttributeSet attrs) {  
        super(context, attrs);  
    }  
  
    @Override  
    protected void onDraw(Canvas canvas) {  
        Paint paint = new Paint();  
        paint.setTextSize(20);  
        paint.setColor(Color.GRAY);  
        canvas.drawText("输入提示文本:", 10, getHeight() / 2 + 5, paint);  
        super.onDraw(canvas);  
    }  
}  
 
main.xml:
[html]  
<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:id="@+id/linearlayout"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:orientation="horizontal" >  
  
    <Button  
        android:id="@+id/button2"  
        android:layout_width="80dp"  
        android:layout_height="80dp"  
        android:layout_alignParentTop="true"  
        android:layout_centerHorizontal="true"  
        android:layout_marginTop="150dp"  
        android:onClick="click"  
        android:text="Button" />  
  
</RelativeLayout>  
 

Android--动态添加控件