Setting parameters on child views of a RelativeLayout

10,322

Solution 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);
    }

}

You only need ALIGN_PARENT_RIGHT if you want the right edge of the view to line up with the right edge of its parent. In this case, it would push the 'first' view off the side of the visible area!

Solution 2

Falmarri, you'll need to use the 'addRule(int)' method.

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

The full list of constants that can be used for addRule can be found here: http://developer.android.com/reference/android/widget/RelativeLayout.html

And here is the addRule method reference: http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#addRule(int,%20int)

Share:
10,322
Falmarri
Author by

Falmarri

Updated on June 04, 2022

Comments

  • Falmarri
    Falmarri almost 2 years

    I'm having trouble finding exactly the syntax I need to use to set the paramters on child views of a relative layout. I have a root relative layout that I want to set 2 child textviews next to each other like this

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

    So I have

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

    How do I set the relative alignments?

  • Falmarri
    Falmarri over 13 years
    Yeah my code is kind of wrong. That's what I'm doing, first is align_parent_right, and then second is align_left_of first.id()