使用RelativeLayout动态添加View总结

来源:互联网 发布:linux 局域网聊天 编辑:程序博客网 时间:2024/05/18 01:26

有篇原文http://lovesong.blog.51cto.com/3976862/1183335


在很多时候xml里面的布局并不能满足我们的需求。这时候就需要用代码进行动态布局,前些天在对RelativeLayout 进行动态布局时遇到了些问题,现在解决了,分享下。

我现在在RelativeLayout 里面 动态创建4个View,是两行两列的效果。

1.添加第一个View。

RelativeLayout layout = (RelativeLayout)findViewById(R.layout.rl);

ImageView item1 = new ImageView(this);

item1.setImageResource(R.drawable.x);//设置图片

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(

LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);//与父容器的左侧对齐

lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);//与父容器的上侧对齐

lp.leftMargin=30;

lp.topMargin=30;

item1.setId(1);//设置这个View 的id 

item1.setLayoutParams(lp);//设置布局参数

layout.addView(item1);//RelativeLayout添加子View

2.添加第二个View。

ImageView item2 = new ImageView(this);

item2.setImageResource(R.drawable.x);//设置图片

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(

LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);

lp.rightMargin=30;

lp.topMargin=30;

item2.setId(2);

item2.setLayoutParams(lp);

 

layout.addView(item2);

 3.添加第三个View。

View childView1 = skinsLayout.getChildAt(0);刚加进去RelativeLayout的第一个子View

View item3 =createSkinItem(friendContext);

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(

LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

lp.addRule(RelativeLayout.BELOW,  childView1.getId());//设置item3在     //chlidView1的下面

lp.leftMargin=30;

lp.topMargin=30;

item3.setId(3);

item3.setLayoutParams(lp);

 

layout.addView(item3);

 3.添加第四个View。

View childView2 = skinsLayout.getChildAt(1);//获取容器的第二个子view 

ImageView item4 = new ImageView(this);

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(

LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

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

lp.rightMargin=30;

lp.topMargin=30;

item4.setId(4);

item4.setLayoutParams(lp);

 

layout.addView(item4);


上面的方法OK啦,我碰到的问题是需要使用

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

params.addRule(RelativeLayout.ABOVE, R.id.detailreply_content);

就是above,在指定的view id上面,可是由于android的layout的View视图渲染顺序的问题,使用ABOVE无法显示使用relativelayout添加的view

但是使用BELOW却可以完成,显示添加的view在指定的view id之下。

然后通过这个RelativeLayout.addView("指定的view视图","上面的params");


3 2
原创粉丝点击