CL So CL So - 1 month ago 7
Android Question

How to make image distributed to screen width in RelativeLayout?

I have three icon the a RelativeLayout, how to make them distributed to screen width?

Since I may add more icon to this line programmatically, I cannot hard code a fixed margin to these icon.

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="@+id/icon1"
android:src="@mipmap/icon" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="@+id/icon2"
android:layout_toRightOf="@id/icon1"
android:layout_alignBottom="@id/icon1"
android:src="@mipmap/icon" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="@+id/icon3"
android:layout_toRightOf="@id/icon2"
android:layout_alignBottom="@id/icon2"
android:src="@mipmap/icon" />
</RelativeLayout>

Answer

Please use LinearLayout and use this code, which will work in all resolutions device.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="3" >

        <ImageView
            android:id="@+id/icon1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher" />

        <ImageView
            android:id="@+id/icon2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/icon1"
            android:layout_toRightOf="@id/icon1"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher" />

        <ImageView
            android:id="@+id/icon3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/icon2"
            android:layout_toRightOf="@id/icon2"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>

</LinearLayout>