views:

128

answers:

2

I have a linear layout (oriented horizontally) that contains 3 buttons. I want the 3 buttons to have a fixed width and be evenly distributed across the width of the linear layout.

I can manage this by setting the gravity of the linearlayout to center and then adjusting the padding of the buttons, but this works for a fixed width and won't work for changing devices or orientations.

<LinearLayout android:id="@+id/LinearLayout01" 
android:layout_height="wrap_content" 
android:orientation="horizontal" 
android:layout_width="fill_parent" 
android:gravity="center">

<Button 
android:id="@+id/btnOne"
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:width="120dip"></Button>

<Button 
android:id="@+id/btnTwo"
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:width="120dip"></Button>


<Button 
android:id="@+id/btnThree"
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:width="120dip"></Button>

</LinearLayout>
A: 

You should take a look to android:layout_weight attribute

fedj
It was my understanding that the layout_weight attribute will stretch the size of the button to fill the layout. I want to keep the size of the buttons constant and just increase the padding between the buttons.
isolatedIterator
Ah ! I don't really know the best way to do it. Perhaps enclosing each button in layout. The 3 layout with layout_weight attribute and the button centered in the layout. But I really don't know if it is the best way to do it.
fedj
A: 

Expanding on fedj's answer, if you set layout_width to 0dp and set the layout_weight for each of the buttons to 1, the available width will be shared equally between the buttons.

Dan Dyer
To expand on this, if you don't want the width of the buttons to be 1/3rd of the screen, wrap each button in a LinearLayout and set layout_width="0dp" and layout_weight="1" on the 3 LinearLayouts. Additionally, set the gravity on the LinearLayouts to "center" so the buttons will align in the center of each LinearLayout.
Andrew