代码控制子控件对象
- 创建布局资源
- 绑定布局
- new 控件并设置属性
- 向布局添加控件
设置控件属性必须通过相对应的布局类型下的参数
private LinearLayout root;
private Button Click;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
root =new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
setContentView(root);
for(int i=0;i<5;i++) {
Click = new Button(this);
Click.setText("点击");
Click.setOnClickListener(this);
LinearLayout.LayoutParams lp =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.MATCH_PARENT);
lp.weight=1; //设置占比
root.addView(Click,lp);
}
相对布局
可以将控件相对于父级容器和其他控件进行布局,更加的灵活
private android.widget.RelativeLayout root;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
root =new android.widget.RelativeLayout(this);
setContentView(root);
tv =new TextView(this);
tv.setText("nihao");
android.widget.RelativeLayout.LayoutParams lp = new android.widget.RelativeLayout.LayoutParams(android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.leftMargin =500;
lp.topMargin=500;
root.addView(tv,lp);
}