手动创立RelativeLayout

来源:互联网 发布:视频导出图片软件 编辑:程序博客网 时间:2024/06/11 14:55

为何要手动创立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


原创粉丝点击