How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?


I have a relative layout which I am creating programmatically:

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

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


Now I want to know how can I programmatically set the the android:layout_alignParentRight="true" or android:layout_toLeftOf="@id/btn" attribute of buttons as we do in the xml?

11/17/2018 12:55:00 AM

Accepted 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)button.getLayoutParams();

button.setLayoutParams(params); //causes layout update
5/9/2013 10:58:16 PM

  1. you need to create and id for the buttons you need to refference: btn1.setId(1);
  2. you can use the params variable to add parameters to your layout, i think the method is addRule(), check out the android java docs for this LayoutParams object.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow