Search code examples
androidandroid-relativelayout

Textview comes on top Imageview


I'm trying to add a TextView and an ImageView in a RelativeLayout, as follows

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:paddingTop="10dp"
    xmlns:android="http://schemas.android.com/apk/res/android">


        <TextView
            android:background="@drawable/bg_message2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore"
            android:textSize="16dp"
            android:id="@+id/mUser"/>
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/mUserImg"
            android:layout_alignParentRight="true"
            android:background="@drawable/bg_profile_message"/>

</RelativeLayout>

The above code looks like this: https://i.sstatic.net/5vhsc.png

and What I want : https://i.sstatic.net/PVDIK.jpg

how do I prevent the TextView being underlaid on the ImageView?


Solution

  • First set the ImageView in place, then set the TextView.
    You can give the TextView a width of "match_parent", because it will fill just the remaining space.

    So:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:paddingTop="10dp"
        xmlns:android="http://schemas.android.com/apk/res/android"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/mUserImg"
            android:layout_alignParentRight="true"
            android:background="@drawable/bg_profile_message"
        />
        <TextView
            android:background="@drawable/bg_message2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_toLeftOf="@id/mUserImg"
            android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore"
            android:textSize="16dp"
            android:id="@+id/mUser"
        />
    </RelativeLayout>