Search code examples
androidandroid-relativelayout

How to place a Textview to the right and center of the Imageview in Relative Layout


I want to place a textview to the right and gravity centre of the Image View. I am using Relative Layout for that. Using Relative Layout, i am able to set the Textview to the right side of the Image view.But not able to set it to the centre. I mean here center is not inside of the Imageview, i want to place Textview to the right centre of Imageview(outside centre of Imageview).I am not able to set to centre. Anybody please help me out.I want to do this only in relative layout.

Here is my xml,

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_marginTop="60dp"
    android:layout_width="match_parent">
    <TextView
        android:id="@+id/name_text_view"
        android:textSize="20sp"
        android:layout_toRightOf="@id/image_view"
        android:layout_width="wrap_content"
        android:textColor="@color/black"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"/>
    <ImageView
        android:id="@+id/image_view"
        android:layout_marginLeft="30dp"
        android:layout_width="50dp"
        android:layout_height="50dp"/>
    <Button
        android:id="@+id/button"
        android:layout_centerHorizontal="true"
        android:background="@color/blue"
        android:textColor="@color/color_white"
        android:layout_marginTop="20dp"
        android:layout_below="@id/name_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/val_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:layout_marginTop="20dp"
        android:textSize="18sp"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/button"/>
</RelativeLayout>

Solution

  • You can do it with this code:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="60dp">
    
    
    <ImageView
        android:id="@+id/image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:scaleType="center"
        android:src="@drawable/ic_launcher_background" />
    
    
    <TextView
        android:id="@+id/name_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/image_view"
        android:layout_centerInParent="true"
        android:text="hello world"
        android:textColor="@color/black"
        android:textSize="12sp" />
    
    </RelativeLayout>