Java – How to set the align parent right attribute of TextViews in relative layout programmatically

androidandroid-relativelayoutjavalayoutparamsxml

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?

Best Answer

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
Related Topic