Search code examples
androidxmlandroid-layoutandroid-linearlayout

Make linear layout spread icons evenly without stretching the icons


I have a horizontal linear layout. with 4 image buttons. I want to distribute these evenly of the width of the screen.

Normally I would do this by setting the layout widths of the icons to 0dp, and weights to 1. Then I would set the the linear layout wight sum to 4 as below.

However when I do this it stretches the button.

How do you distribute them evenly without icon stretching and without having to use a relative layout and set margins?

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         android:weightSum="4">

        <ImageButton
            android:id="@+id/mainAlarmButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_alarm_white_18dp"/>

        <ImageButton
            android:id="@+id/addAlarmButton"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/ic_add_white_18dp"/>

        <ImageButton
            android:id="@+id/shareButton"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/ic_share_white_18dp"/>

        <ImageButton
            android:id="@+id/settingsButton"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/ic_tune_white_18dp"/>

    </LinearLayout>

Thanks for your help


Solution

  • I would suggest you to use ImageView instead of ImageButton, then instead of android:background use android:src. Then with using proper android:scaleType you can achieve what you want.