Search code examples
androidandroid-relativelayoutlayout-gravity

Android: gravity ImageView in RelativeLayout failed


I would like to align this ImageView in center (horizontal and vertical):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/titletab"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="@dimen/slidingtab_icon_header"
    android:gravity="center">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="@dimen/slidingtab_item_icon_size"
        android:layout_height="@dimen/slidingtab_item_icon_size"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/ic_event_black_18dp"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_alignParentBottom="true"
        android:background="@color/sliding_tab_border_color"/>

</RelativeLayout>

If I don't add the line (the View) after my ImageView it's perfect, it's work, but with this line the gravity doesn't work.

Thanks by advance!


Solution

  • You need to change some property and your view is perfect. Just check below and you see I change gravity property in .

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/titletab"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="@dimen/slidingtab_icon_header"
        >
    
        <ImageView
            android:id="@+id/icon"
            android:layout_width="@dimen/slidingtab_item_icon_size"
            android:layout_height="@dimen/slidingtab_item_icon_size"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:src="@drawable/ic_launcher"/>
    
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_alignParentBottom="true"
            android:background="@color/sliding_tab_border_color"/>
    
    </RelativeLayout>
    

    You need to use

    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    

    instead of

    android:layout_gravity="center_horizontal|center_vertical"
    

    because This is works in LinearLayout. But, for RelativeLayout you need to use above property for gravity set.