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


Question

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>
1
223
8/12/2010 5:36:14 PM

Accepted 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.

314
5/23/2017 12:03:05 PM

If you don't want the buttons to scale, but adjust the spacing between the buttons (equal spacing between all buttons), you can use views with weight="1" which will fill the space between the buttons:

    <Space
        android:layout_width="0dp"
        android:layout_height="1dp"
        android:layout_weight="1" >
    </Space>

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:background="@null"
        android:gravity="center_horizontal|center_vertical"
        android:src="@drawable/tars_active" />

    <Space
        android:layout_width="0dp"
        android:layout_height="1dp"
        android:layout_weight="1" >
    </Space>

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:background="@null"
        android:gravity="center_horizontal|center_vertical"
        android:src="@drawable/videos_active" />

    <Space
        android:layout_width="0dp"
        android:layout_height="1dp"
        android:layout_weight="1" >
    </Space>

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon