手动创立RelativeLayout

为何要手动创立RelativeLayout?

-->总有原因的,如果实在没有原因,那最好还是通过xml文件来建立;


要点:要为每一个child view生成一个LayoutParams.


实施:

RelativeLayout root_layout = new RelativeLayout(context);

ImageView img_view          = new ImageView(context);

RelativeLayout.LayoutParams img_lp = new RelativeLayout.LayoutParams(img_width, img_height);

img_lp.topMargin = img_top_margin;

img_lp.leftMargin= img_left_margin;

root_layout.addView(img_view, img_lp);


TextView text_view = new TextView(context);

RelativeLayout.LayoutPrams text_lp = new RelativeLayout.LayoutParams(text_width, text_height);

text_lp.topMargin = text_top_margin;

text_lp.leftMargin = text_left_margin;

root_layout.addView(text_view, text_lp);


错误的方式:使用同一个LayoutParams设置多个View. 最后生成root_layout时的LayoutParams只采用最后一次设置的数值,将导致错误的布局。

RelativeLayout root_layout = new RelativeLayout(context);

ImageView img_view          = new ImageView(context);

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(img_width, img_height);

img_lp.topMargin = img_top_margin;

img_lp.leftMargin= img_left_margin;

root_layout.addView(img_view, lp);


TextView text_view = new TextView(context);

lp.height = text_height;

lp.width  = text_width;

lp.topMargin = text_top_margin;

lp.leftMargin = text_left_margin;

root_layout.addView(text_view, lp);

---->Wrong layout..


其他的LayoutParams设置:

切以为使用MarginLayout中的数值即可满足布局的要求,要充分发挥RelativeLayout.LayoutParams的功效还可以通过addRule()来设置相对布局,前提是在生成view的时候设置其id(setId),具体请参考:http://www.mergeconflict.net/2010/08/manually-positioning-views-in.html


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值