1.动态添加2个垂直排列的Button
1 @Override 2 public void onCreate(Bundle savedInstanceState) { 3 super.onCreate(savedInstanceState); 4 //setContentView(R.layout.main); 5 final LinearLayout layout2=new LinearLayout(this); 6 layout2.setOrientation(LinearLayout.VERTICAL); 7 Button btn1=new Button(this); 8 setContentView(layout2); 9 Button btn2=new Button(this); 10 btn1.setText("Button1"); 11 btn2.setText("Button2"); 12 layout2.addView(btn1); 13 layout2.addView(btn2); 14 15 16 setContentView(layout2); 17 }
final LinearLayout layout2=new LinearLayou(this);
定义一个LinearLayout ,参数为context在这儿即为this
layout2.setOrientation(LinearLayout.VERTICAL);
设置layout格式为vertical,竖直排列
2.在Button的click事件中动态添加一个button
1 OnClickListener listen1; 2 @Override 3 public void onCreate(Bundle savedInstanceState) { 4 super.onCreate(savedInstanceState); 5 //setContentView(R.layout.main); 6 final LinearLayout layout2=new LinearLayout(this); 7 layout2.setOrientation(LinearLayout.VERTICAL); 8 Button btn1=new Button(this); 9 setContentView(layout2); 10 Button btn2=new Button(this); 11 btn1.setText("Button1"); 12 btn2.setText("Button2"); 13 layout2.addView(btn1); 14 layout2.addView(btn2); 15 listen1 = new OnClickListener() { 16 public void onClick(View v) { 17 setTitle("点击button1 "); 18 Button btn3=new Button(v.getContext()); 19 layout2.addView(btn3); 20 btn3.setText("Button3"); 21 22 23 } 24 }; 25 btn1.setOnClickListener(listen1); 26 }