在RelativeLayout的子视图上设置参数

时间:2010-10-07 19:15:56

标签: android android-layout relativelayout

我很难找到我需要用来在相对布局的子视图上设置参数的语法。我有一个根相对布局,我想将2个子文本视图设置为彼此相邻,如下所示

---------- ---------
| Second | | First |
---------- ---------

所以我有

public class RL extends RelativeLayout{

    public RL(context){

        TextView first = new TextView(this);
        TextView second = new TextView(this);

        first.setText('First');
        first.setId(1);

        second.setText('Second');
        second.setId(2);

        addView(first, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
    LayoutParams.WRAP_CONTENT, 
    LayoutParams.ALLIGN_PARENT_RIGHT ???);

        addView(first, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
    LayoutParams.WRAP_CONTENT, 
    LayoutParams.ALLIGN_RIGHT_OF(first.getId()) ???);

    }
}

如何设置相对比对?

2 个答案:

答案 0 :(得分:14)

public class RL extends RelativeLayout {

    public RL(Context context) {
        super(context);

        TextView first = new TextView(context);
        TextView second = new TextView(context);

        first.setText("First");
        first.setId(1);

        second.setText("Second");
        second.setId(2);

        RelativeLayout.LayoutParams lpSecond = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        addView(second, lpSecond);

        RelativeLayout.LayoutParams lpFirst = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        lpFirst.addRule(RelativeLayout.RIGHT_OF, second.getId());
        addView(first, lpFirst);
    }

}

如果您希望视图的右边缘与其父边缘对齐,则只需要ALIGN_PARENT_RIGHT。在这种情况下,它会将“第一个”视图推离可见区域的一侧!

答案 1 :(得分:3)

Falmarri,你需要使用'addRule(int)'方法。

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams
    (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RIGHT_OF, first.getId());

可以在此处找到可用于addRule的常量的完整列表: http://developer.android.com/reference/android/widget/RelativeLayout.html

这是addRule方法参考: http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#addRule(int,%20int