0

我正在尝试以编程方式添加 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);
4

3 回答 3

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);
于 2013-08-14T10:36:26.857 回答
0

您必须指定TextView和在ImageView各自LayoutParams. 您可以使用该addRule方法来执行相同的操作。

例如:

item.setId(A_POSITIVE_INTEGER);
myparam.addRule(RelativeLayout.BELOW, item.getId());
tv.setLayoutParams(myparam);

将使TextView出现在ImageView.

于 2013-08-14T10:20:29.927 回答
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);
于 2013-08-14T10:22:52.373 回答