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);
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,其他控件同样格式加载
本文介绍如何在Android中动态创建各种控件,以相对布局(RelativeLayout)为例,探讨通过RelativeLayout.LayoutParams实现控件的位置设定。重点讲解了TextView的创建过程。
2313

被折叠的 条评论
为什么被折叠?



