我正在尝试以编程方式添加RelativeLayout。布局包含水平的imageview和textview。现在两者都重叠了。如何以编程方式使用LayoutParams正确设置对齐?
RelativeLayout rl = new RelativeLayout(this);
RelativeLayout.LayoutParams myparam = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
TextView tv = new TextView(this);
tv.setText("test");
tv.setTextColor(Color.WHITE);
ImageView item = new ImageView(this);
item.setImageResource(image);
myparam.addRule(RelativeLayout.ALIGN_RIGHT);
tv.setLayoutParams(myparam);
rl.addView(item);
rl.addView(tv);
答案 0 :(得分:2)
Check this code now..this will help
RelativeLayout rl = new RelativeLayout(this);
RelativeLayout.LayoutParams myparam = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams newParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ImageView item = new ImageView(this);
item.setImageResource(image);
item.setId(1);
item.setLayoutParams(newParams);
rl.addView(item);
RelativeLayout.LayoutParams lprams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
TextView tv = new TextView(this); tv.setText("test");
tv.setTextColor(Color.WHITE);
tv.setLayoutParams(lprams);
lprams.addRule(RelativeLayout.RIGHT_OF, 1);
rl.addView(tv);
答案 1 :(得分:0)
您必须在各自的TextView
中指定ImageView
和LayoutParams
相关的方式。您可以使用addRule
方法执行相同的操作。
对于egs:
item.setId(A_POSITIVE_INTEGER);
myparam.addRule(RelativeLayout.BELOW, item.getId());
tv.setLayoutParams(myparam);
会使TextView
显示在ImageView
下方。
答案 2 :(得分:0)
试试这段代码
RelativeLayout rl = new RelativeLayout(this); RelativeLayout.LayoutParams myparam = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams lprams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
TextView tv = new TextView(this); tv.setText("test");
tv.setId(1);
tv.setTextColor(Color.WHITE);
tv.setLayoutParams(lprams);
rl.addView(tv);
RelativeLayout.LayoutParams newParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ImageView item = new ImageView(this);
item.setImageResource(image);
newParams.addRule(RelativeLayout.RIGHT_OF, 1);
item.setLayoutParams(newParams);
rl.addView(item);