【问题标题】:Setting parameters on child views of a RelativeLayout在 RelativeLayout 的子视图上设置参数
【发布时间】:2010-10-07 19:15:55
【问题描述】:

我无法准确找到我需要用来在相对布局的子视图上设置参数的语法。我有一个根相对布局,我想像这样设置 2 个彼此相邻的子文本视图

---------- --------- |第二 | |第一 | ---------- ---------

所以我有

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()) ???);

    }
}

如何设置相对对齐方式?

【问题讨论】:

    标签: android android-layout android-relativelayout


    【解决方案1】:
    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。在这种情况下,它会将“第一个”视图推离可见区域的一侧!

    【讨论】:

    • 是的,我的代码有点错误。这就是我正在做的,首先是align_parent_right,然后是align_left_of first.id()
    【解决方案2】:

    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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 2011-10-05
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多