1.绝对布局,动态添加组件:
AbsoluteLayout abslayout = new AbsoluteLayout (this);
setContentView(abslayout);
Button btn1 = new Button(this);
btn1.setText(”this is a button”);
btn1.setId(1);
//设置布局的参数,设置布局的大小范围
AbsoluteLayout.LayoutParams lp1 = new AbsoluteLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,0,100);
//添加组件
abslayout.addView(btn1, lp1);
2.相对布局,动态添加组件:
RelativeLayout relativeLayout = new RelativeLayout(this);
setContentView(relativeLayout);
AbsoluteLayout abslayout=new AbsoluteLayout (this);
//设置布局的参数,设置布局的大小范围
RelativeLayout.LayoutParams lp1 = newRelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp1.addRule(RelativeLayout.CENTER_HORIZONTAL,RelativeLayout.TRUE);
relativeLayout.addView(abslayout ,lp1);
3.线性布局,动态添加组件。
LinearLayout linearLayout = new LinearLayout(this);
EditText et = new EditText();
linearLayout.addView(et);
4.动态添加布局的方法:
1)动态添加布局方法1,通过inflate方法把linearLayout1当成linearLayout2的父节点添加进去:
LinearLayout linearLayout1 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main1,null);
setContentView(linearLayout1);
//这样 main2 作为 main1的子布局 加到了 main1的 根节点下,通过inflate方法把linearLayout1当成linearLayout2的父节点添加进去
LinearLayout linearLayout2 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main2, linearLayout1);
2)动态添加布局方法2,还有一种就是通过addView方式,把linearLayout2添加到linearLayout1里面去):
LinearLayout linearLayout1 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main1,null);
setContentView(linearLayout1);
LinearLayout linearLayout2 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main2,null);
//通过ViewGroup的addView方法把linearLayout2添加到linearLayout1里面去。
linearLayout1.addView(linearLayout2);