4

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?

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
Falmarri
  • 47,727
  • 41
  • 151
  • 191

2 Answers2

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

}

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!

Andy
  • 4,039
  • 1
  • 20
  • 15
  • 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() – Falmarri Oct 08 '10 at 00:22
3

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)

Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274