代码设置RelativeLayout相对位置设置

 
  

在XML中,RelativeLayout相对位置使用android:layout_toRightOf="@+id/view0"来设置;代码中:

ImageView image = new ImageView(context);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.RIGHT_OF, text.getId());
rl.addView(image, lp);

需要注意,相对的控件如果是new出来的TextView text = new TextView(context);,需要调用setId()设置ID,text.setId(Integer.MAX_VALUE - 1000);,否则不生效。
2016-12-02发现了点问题
之前图片相对在文字右边,高度差不多,没看出问题,今天换了个长图片就发现高度不是居中了。
调了一下,贴一下正确代码

    
        
    
TextView text = new TextView(context);
text.setId(Integer.MAX_VALUE - 1000);
text.setTextSize(16);
text.setText("文字");
text.setPadding(0,0,3,0);
text.setTextColor(ContextCompat.getColorStateList(context,R.color.a));
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
addView(text, params);

ImageView imageView = new ImageView(context);
imageView.setImageDrawable(isUp ? drawableUp :drawableDown);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
lp.addRule(RelativeLayout.RIGHT_OF , text.getId());
addView(imageView, lp);

因为是居中,所以不管是在XML还是在代码中,第一个控件一定要写android:layout_centerInParent这个属性,第二个可以android:layout_centerVertical="true"android:layout_centerInParent="true",也要写上,否则无效。代码中第二个的addRule()方法,两个记得要分开写,刚开始写一块lp.addRule(RelativeLayout.CENTER_IN_PARENT|RelativeLayout.RIGHT_OF , text.getId());显示出来很奇怪。效果如图:

代码设置RelativeLayout相对位置设置_第1张图片

你可能感兴趣的:(#,android,Ui效果)