yamspog yamspog - 5 months ago 19
Android Question

is it possible to evenly distribute buttons across the width of an android linearlayout

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>

Answer

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.