Android 利用addView 让Activity 动态加入多个View 物件

在Android 中,

你可以利用排版View的 addView 函数,

将动态产生的View 物件加入到排版View 中,

范例如下 :

main.xml 部分内容

Java 程式码

public class helloWorld extends Activity {
 
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView( R.layout.main );
 
      // 取得LinearLayout 物件
      LinearLayout ll = (LinearLayout)findViewById(R.id.viewObj);
 
      // 将TextView 加入到LinearLayout 中
      TextView tv = new TextView(this);
      tv.setText("Hello World");
      ll. addView ( tv );
 
      // 将Button 1 加入到LinearLayout 中
      Button b1 = new Button(this);
      b1.setText("取消");
      ll. addView ( b1 );
 
      // 将Button 2 加入到LinearLayout 中
      Button b2 = new Button(this);
      b2.setText("确定");
      ll. addView ( b2 );
 
      // 从LinearLayout 中移除Button 1
      ll. removeView ( b1 );
   }
}

范例结果 :

原文链接:http://tomkuo139.blogspot.com/2010/01/android-addview-activity-view.html

你可能感兴趣的:(Android 利用addView 让Activity 动态加入多个View 物件)