Search code examples
androidandroid-layoutbuttonandroid-linearlayout

Equal space between buttons in a LinearLayout


I have four buttons arranged vertically in a LinearLayout.

buttons

I want the space between the buttons and the space between the topmost button and the top of the linear layout and the space between the bottom most button and the bottom of the layout, to be the same.

In the attached figure, the spaces are depicted as red paths. I want all the spaces to be of the same size.

How would I go about achiving my goal?

<LinearLayout
            p1:orientation="vertical"
            p1:layout_width="wrap_content"
            p1:layout_height="wrap_content"
            p1:id="@+id/mainButtonLayout">
            <Button
                p1:text="xxx"
                p1:layout_width="match_parent"
                p1:layout_height="wrap_content"
                p1:id="@+id/saButton"
                p1:textColor="#FFFFFF"
                p1:background="@drawable/roundedBlue"
                p1:minHeight="33dp"
                p1:minWidth="175dp"
                p1:layout_marginBottom="20dp" />
            <Button
                p1:text="xxxx"
                p1:layout_width="match_parent"
                p1:layout_height="wrap_content"
                p1:id="@+id/rButton"
                p1:textColor="#FFFFFF"
                p1:background="@drawable/roundedBlue"
                p1:minHeight="33dp"
                p1:minWidth="175dp"
                p1:layout_marginBottom="20dp" />
            <Button
                p1:text="xxxxx"
                p1:layout_width="match_parent"
                p1:layout_height="wrap_content"
                p1:id="@+id/sButton"
                p1:textColor="#FFFFFF"
                p1:background="@drawable/roundedBlue"
                p1:minHeight="33dp"
                p1:minWidth="175dp"
                p1:layout_marginBottom="20dp" />
            <Button
                p1:text="xxxxx"
                p1:layout_width="match_parent"
                p1:layout_height="wrap_content"
                p1:id="@+id/pButton"
                p1:textColor="#FFFFFF"
                p1:background="@drawable/roundedBlue"
                p1:minHeight="33dp"
                p1:minWidth="175dp" />
        </LinearLayout>

Solution

  • Use weightsum in your LinearLayout

    <LinearLayout
    ...
    android:weightSum="4.0">`
    

    In every Button put layout_height = 0dp , layout_weight = 1, top and bottom margin according to your need but same in every button.

    <Button....
    ...
    android:layout_height="0dp"
    android:layout_weight="1.0"
    android:layout_marginBottom="40dp"
    android:layout_marginTop="40dp"
    />
    

    for more info : read this document