Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to evenly distribute buttons across the width of a LinearLayout

I have a LinearLayout (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 LinearLayout.

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 different devices or orientations.

<LinearLayout     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:gravity="center"     android:orientation="horizontal">      <Button         android:id="@+id/btnOne"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:width="120dp" />      <Button         android:id="@+id/btnTwo"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:width="120dp" />       <Button         android:id="@+id/btnThree"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:width="120dp" /> </LinearLayout> 
like image 782
yamspog Avatar asked Aug 12 '10 17:08

yamspog


People also ask

Is it possible to evenly distribute buttons across the width of an android LinearLayout?

I suggest you use LinearLayout's weightSum attribute. Adding the tag android:weightSum="3" to your LinearLayout's xml declaration and then android:layout_weight="1" to your Buttons will result in the 3 buttons being evenly distributed.

What is orientation property in LinearLayout?

LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally. You can specify the layout direction with the android:orientation attribute.

What is a relative layout?

RelativeLayout is a view group that displays child views in relative positions. The position of each view can be specified as relative to sibling elements (such as to the left-of or below another view) or in positions relative to the parent RelativeLayout area (such as aligned to the bottom, left or center).


1 Answers

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.

like image 200
Dan Dyer Avatar answered Sep 19 '22 18:09

Dan Dyer