Falmarri
Falmarri

Reputation: 48577

Setting parameters on child views of a RelativeLayout

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?

Upvotes: 4

Views: 10425

Answers (2)

Andy
Andy

Reputation: 4039

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!

Upvotes: 14

Kevin Coppock
Kevin Coppock

Reputation: 134664

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)

Upvotes: 3

Related Questions