Search code examples
androidxmllayoutalignment

How to display image in center across resolutions


I have a layout in which one of the inside doesn't come in center, It happens only in few resolution devices, whereas in few it comes perfectly in center. Below is code and screenshot

<ImageView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:gravity="center"
                android:src="@drawable/thank" android:paddingTop="10dip"
                android:paddingBottom="10dip"/>

Code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/splash_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:gravity="center" android:orientation="vertical"
    android:background="@drawable/background">

    <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:gravity="center_horizontal"
        android:src="@drawable/logo" android:paddingTop="10dip"
        android:paddingBottom="10dip" />

     <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <ImageView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:gravity="center"
            android:src="@drawable/thank" android:paddingTop="10dip"
            android:paddingBottom="10dip"/>

        <com.teleca.sam.ui.Copyright
            android:layout_width="fill_parent" android:layout_height="fill_parent"
            android:gravity="bottom|center"/>
    </RelativeLayout>
</LinearLayout>

Solution

  • If you are using a LinearLayout:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">
    
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageView"
            android:layout_gravity="center_horizontal"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>
    

    If you are using a RelativeLayout:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageView"
            android:src="@drawable/ic_launcher"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />
    </RelativeLayout>