2

I have a relative layout which I am creating programmatically:

 RelativeLayout layout = new RelativeLayout( this );
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
        LayoutParams.WRAP_CONTENT);

Now I have two TextViews which I want to add in this relative layout. But the problem is both TextViews are being shown on the left of the RelativeLayout overlapping on each other.

textViewContainer.addView(textView1);
textViewContainer.addView(textView2);

Now I want to know how can I programmatically set the the

`android:layout_alignParentRight="true"`

or

`android:layout_toLeftOf="@id/textView"` 

attribute of TextViews as we do in the xml?

SoftIdea
  • 47
  • 1
  • 5
  • This answer might help: http://stackoverflow.com/questions/4638832/how-to-programmatically-set-the-layout-align-parent-right-attribute-of-a-button – sri Feb 02 '17 at 07:54
  • Possible duplicate of [How to programmatically set the layout\_align\_parent\_right attribute of a Button in Relative Layout?](http://stackoverflow.com/questions/4638832/how-to-programmatically-set-the-layout-align-parent-right-attribute-of-a-button) – RubioRic Feb 02 '17 at 07:56

3 Answers3

5

You can access any LayoutParams from code using View.getLayoutParams. You just have to be very aware of what LayoutParams your accessing. This is normally achieved by checking the containing ViewGroup if it has a LayoutParams inner child then that's the one you should use. In your case it's RelativeLayout.LayoutParams. You'll be using RelativeLayout.LayoutParams#addRule(int verb) and RelativeLayout.LayoutParams#addRule(int verb, int anchor)

You can get to it via code:

   RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)textView.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);

textView.setLayoutParams(params); //causes layout updat
Shafqat Kamal
  • 439
  • 4
  • 12
0

Use the method addrule

params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
Madhav
  • 283
  • 3
  • 13
0

You need to align LayoutParams to each view:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

Then add appropriate rule to each view:

params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 

to the first one and

params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);

to the second one.

then apply it to the view:

view.setLayoutParam(params)
R. Zagórski
  • 20,020
  • 5
  • 65
  • 90