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>
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With