Search code examples
androidandroid-layoutdynamicandroid-imageviewandroid-relativelayout

How to float images right in Android RelativeLayout?


I want to display a text and next to the text a dynamic number of images that should be floated to the right side.

That is what I have:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:padding="7dp"
        android:textSize="18sp"
        android:textColor="#000"/>

    <ImageView
        android:id="@+id/icon1"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:gravity="right"
        android:layout_alignParentRight="true"
        android:layout_marginTop="10dip"
        android:layout_marginRight="6dip"
        android:src="@drawable/bus" />

    <ImageView
        android:id="@+id/icon2"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_toLeftOf="@+id/1"
        android:layout_marginTop="10dip"
        android:layout_marginRight="6dip"
        android:src="@drawable/tram" />

</RelativeLayout>

My problem is that if icon1 is not visible (I control on my Java code) icon2 is not displayed on the right side anymore. It overlayed text1, because the referenced icon1 is missing.


Solution

  • Well, either your layout above is incomplete (and if so you should post the full thing) or your ids are broken (you've laid out icon2 to the left of @+id/1 when it should be to the left of @+id/icon1.

    Try setting android:layout_alignWithParentIfMissing="true" on icon2 and correct the layout ids.