relativelayout中心对齐,如何动态地通过code在Android的对齐RelativeLayout的视图元素?...

I want to display 3 check box one below each other in relative layout dynamically through code.But i am able to display only two check box one below each other. I am giving below my code....I am not able to find out where i am going wrong.

My Code -

RelativeLayout layout = new RelativeLayout(this);

CheckBox cb1 = new CheckBox(this);

cb1.setId(1);

cb1.setText("A");

CheckBox cb2 = new CheckBox(this);

cb2.setId(2);

cb2.setText("B");

CheckBox cb3 = new CheckBox(this);

cb3.setId(3);

cb3.setText("C");

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(

RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

layout.setLayoutParams(lp);

layout.addView(cb1);

lp.addRule(RelativeLayout.BELOW,cb1.getId());

cb2.setLayoutParams(lp);

layout.addView(cb2);

lp.addRule(RelativeLayout.BELOW,cb2.getId());

cb3.setLayoutParams(lp);

layout.addView(cb3);

Thanks in advance.

Rohan Waugh

解决方案layout.addView(cb1);

lp.addRule(RelativeLayout.BELOW,cb1.getId());

cb2.setLayoutParams(lp);

layout.addView(cb2);

lp.addRule(RelativeLayout.BELOW,cb2.getId());

cb3.setLayoutParams(lp);

layout.addView(cb3);

Thanks man this helped me a lot

I guess you are wrong at the point that you are using "lp" as the layout parameters for both cb2 and cb3(you can't add the same rule "RelativeLayout.BELOW" to same layoutparameters object "lp" again and again).

Use lp for cb2 and lp2 for cb3

and create like this

RelativeLayout layout = new RelativeLayout(this);

CheckBox cb1 = new CheckBox(this);

cb1.setId(1);

cb1.setText("A");

CheckBox cb2 = new CheckBox(this);

cb2.setId(2);

cb2.setText("B");

CheckBox cb3 = new CheckBox(this);

cb3.setId(3);

cb3.setText("C");

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);

layout.setLayoutParams(lp);

layout.addView(cb1);

lp.addRule(RelativeLayout.BELOW,cb1.getId());

cb2.setLayoutParams(lp);

layout.addView(cb2);

RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(

RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);//important

lp2.addRule(RelativeLayout.BELOW,cb2.getId());//important

cb3.setLayoutParams(lp2);//important

layout.addView(cb3);

I think this will work.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值