Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,             LayoutParams.WRAP_CONTENT); 

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.

buttonContainer.addView(btn1); buttonContainer.addView(btn2); 

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?

like image 833
Fahad Ali Avatar asked Jan 09 '11 11:01

Fahad Ali


People also ask

Which attribute or property is specific for RelativeLayout?

RelativeLayout lets child views specify their position relative to the parent view or to each other (specified by ID). So you can align two elements by right border, or make one below another, centered in the screen, centered left, and so on.

How do I center a button in RelativeLayout?

If you have a single Button in your Activity and you want to center it the simplest way is to use a RelativeLayout and set the android:layout_centerInParent=”true” property on the Button.


1 Answers

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(); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);  button.setLayoutParams(params); //causes layout update 
like image 172
Rich Schuler Avatar answered Sep 18 '22 12:09

Rich Schuler