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>

23 Answers
23

Leave a Comment