在Android 中,
你可以利用排版View的 addView 函数,
将动态产生的View 物件加入到排版View 中,
范例如下 :
main.xml 部分内容
- <LinearLayout
- android:id="@+id/viewObj"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="vertical"
- android:layout_x="1px"
- android:layout_y="1px"
- />
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