今天想用java代码写一个在RelativeLayout里面位置在某个View下面居中的View,平时都是用xml代码实现,非常简单,用layout_below属性就可以轻松实现了。于是想当然的在java代码里面也是这样写:
ImageView guide1 = new ImageView(this);
ImageView ib_know = new ImageView(this);
ib_know.setImageResource(R.mipmap.known);
RelativeLayout.LayoutParams guide1_lp = new RelativeLayout.LayoutParams(
ViewUtil.dp2px(this, 328), ViewUtil.dp2px(this, 137));
guide1_lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
guide1_lp.setMargins(0, ViewUtil.dp2px(this, 164), 0, 0);
rl_guide.addView(guide1, guide1_lp);
int ivKnown_width = ViewUtil.dp2px(this, 97);
int ivKnown_height = ViewUtil.dp2px(this, 48);
RelativeLayout.LayoutParams ivKnown_lp = new RelativeLayout.LayoutParams(ivKnown_width, ivKnown_height);
int ivKnown_topMargin = ViewUtil.dp2px(this, 75);
ivKnown_lp.setMargins(0, ivKnown_topMargin, 0, 0);
//设置按钮水平居中置底
ivKnown_lp.addRule(RelativeLayout.BELOW, guide1.getId());
ivKnown_lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
rl_guide.addView(ib_know, ivKnown_lp);
但是结果ib_know 并没有显示在guide1下面,而是显示在了默认位置,设置RelativeLayout.BELOW并没有生效。
为什么呢?呵呵,经过查找解决办法,知道原来这里没有给guide1设置id,所以它的id值默认为-1,所以不生效,那么
ImageView guide1 = new ImageView(this);
guide1.setImageResource(R.mipmap.guide_view_money_transfer);
if (Build.VERSION.SDK_INT >= 17) {
guide1.setId(View.generateViewId()); //此代码要在api level 17以上才能生效
}else{
guide1.setId(R.id.home_fragment_guide_view); //api level在17以下的就在values/ids.xml里配置id
}
ImageView ib_know = new ImageView(this);
ib_know.setImageResource(R.mipmap.known);
RelativeLayout.LayoutParams guide1_lp = new RelativeLayout.LayoutParams(
ViewUtil.dp2px(this, 328), ViewUtil.dp2px(this, 137));
guide1_lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
guide1_lp.setMargins(0, ViewUtil.dp2px(this, 164), 0, 0);
rl_guide.addView(guide1, guide1_lp);
//设置按钮的宽高,间距
int ivKnown_width = ViewUtil.dp2px(this, 97);
int ivKnown_height = ViewUtil.dp2px(this, 48);
RelativeLayout.LayoutParams ivKnown_lp = new RelativeLayout.LayoutParams(ivKnown_width, ivKnown_height);
int ivKnown_topMargin = ViewUtil.dp2px(this, 75);
ivKnown_lp.setMargins(0, ivKnown_topMargin, 0, 0);
//设置按钮水平居中置底
ivKnown_lp.addRule(RelativeLayout.BELOW, guide1.getId());
ivKnown_lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
rl_guide.addView(ib_know, ivKnown_lp);
完美解决。