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

本文介绍如何在Android中动态创建各种控件,以相对布局(RelativeLayout)为例,探讨通过RelativeLayout.LayoutParams实现控件的位置设定。重点讲解了TextView的创建过程。

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,其他控件同样格式加载



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值