Android中利用LinearLayout动态添加控件 - Androider的
专栏 -...
在androidUI布局中,一般都是利用xml来布局控件,这是比较方便和直观的,但是有时却需要动态生成,下面就举2个简单例子来说明怎么动态添加控件: 1.动态添加2个垂直排列的Button view plaincopy to clipboardprint? 01. @Override
02. public void onCreate(Bundle savedInstanceState) { 03. super.onCreate(savedInstanceState); 04. //setContentView(R.layout.main); 05. final LinearLayout layout2=new LinearLayout(this); 06.
layout2.setOrientation(LinearLayout.VERTICAL); 07. Button btn1=new Button(this); 08. setContentView(layout2); 09. Button btn2=new Button(this); 10. btn1.setText(\ 11. btn2.setText(\ 12. layout2.addView(btn1);
13. layout2.addView(btn2); 14. 15.
16. setContentView(layout2); 17.} @Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.main);
final LinearLayout layout2=new LinearLayout(this); layout2.setOrientation(LinearLayout.VERTICAL); Button btn1=new Button(this); setContentView(layout2); Button btn2=new Button(this); btn1.setText(\ btn2.setText(\ layout2.addView(btn1); layout2.addView(btn2);
setContentView(layout2); }
final LinearLayout layout2=new LinearLayou(this); 定义一个LinearLayout ,参数为context在这儿即为this layout2.setOrientation(LinearLayout.VERTICAL); 设置layout格式为vertical,竖直排列
2.在Button的click事件中动态添加一个button view plaincopy to clipboardprint?
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······15001.OnClickListener listen1;