Search code examples
androidxmlimageview

Center ImageView in Relative Layout


I have an image and a textview inside a relative layout. The image and the textview take up 50% of the screen width. How can I center the image and the textview ? I have tried many methods and I don't know what I'm doing wrong...

Here is my code:

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="100">
        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="50"
            android:layout_centerHorizontal="true">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/textViewEventImage"
                android:adjustViewBounds="true" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:background="@color/eventNameBackground"
                android:id="@+id/textViewEventName"
                android:textColor="@android:color/white"
                android:textSize="15sp"/>
        </RelativeLayout>
    </LinearLayout>

enter image description here


Solution

  • Try this code it will suits your requirement

    <?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:orientation="vertical" >
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.5"
            android:background="#ff0000" >
    
        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="180dp"
            android:layout_height="120dp"
            android:layout_centerInParent="true"
            android:gravity="center_vertical"
            android:src="@drawable/americanexpress" />
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_below="@+id/imageView1"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="16dp"
            android:text="Your product" />
    </RelativeLayout>
    
    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.5"
        android:background="#00ff00" />
    
    </LinearLayout>