Android 动态创建各种控件及位置设定

来源:互联网 发布:nginx绑定多个域名 编辑:程序博客网 时间:2024/05/29 18:16

Android 动态创建各种控件及位置设定,以相对布局为例。

位置设定主要由RelativeLayout.LayoutParams控制


1. 创建TextView

final TextView title = new TextView(this);title.setText(Html.fromHtml("<br><b>Your Title</b><br><br>"));//加粗字体title.setId(1);RelativeLayout.LayoutParams titleLP = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);titleLP.leftMargin = 10;titleLP.topMargin = 10;

2. 创建button

final Button activate = new Button(this);activate.setText("Activate");activate.setId(10);RelativeLayout.LayoutParams activeLP = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);activeLP.topMargin = 80;activeLP.addRule(RelativeLayout.BELOW, 8);activeLP.addRule(RelativeLayout.CENTER_HORIZONTAL);

3. 创建radiobutton

final RadioGroup rg = new RadioGroup(this.getApplicationContext());rg.setId(2);RadioButton pk = new RadioButton(this);pk.setText("Radio 1");pk.setId(3);pk.setChecked(true);RadioButton lf = new RadioButton(this);lf.setText("Radio 2");lf.setId(4);rg.addView(pk);rg.addView(lf);


4. 创建checkbox

final CheckBox sslCB = new CheckBox(this);sslCB.setId(7);sslCB.setChecked(false);RelativeLayout.LayoutParams sslCBLP = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);sslCBLP.leftMargin=20;sslCBLP.topMargin=60;sslCBLP.addRule(RelativeLayout.BELOW, 5);sslCBLP.addRule(RelativeLayout.RIGHT_OF, 6);sslCBLP.addRule(RelativeLayout.ALIGN_BASELINE, 6);


5. 创建layout,并且把控件加载进去

layout = new RelativeLayout(this);requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);super.setContentView(layout);
layout.addView(title, titleLP);//加载TextView,其他控件同样格式加载



0 0
原创粉丝点击