Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Center an image

I've got a linear layout and an image...

<?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">  <ImageView android:layout_width="wrap_content" android:id="@+id/imageView1"  android:src="@drawable/icon" android:layout_height="wrap_content"  android:scaleType="center"></ImageView>  </LinearLayout> 

How do I dynamically center my image so that it will appear in the center of the screen on all devices?

like image 232
Skizit Avatar asked May 23 '11 19:05

Skizit


People also ask

How do I center an image in RelativeLayout Android?

RelativeLayout attributes You can change layout_align parent like top, left, and right. android:layout_centerHorizontal : This attribute is used to center the element horizontally within its parent container. You can change layout_center like layout_centerVertical or layout_centerInParent .

How do you center an image in a linear layout?

Try layout_gravity and gravity attributes in the LinearLayout to make all the childs to be centered by default. This above is a splash screen activity. So there are two childs - ImageView and TextView. Both are center aligned.

How do I center an XML view in Android?

You can apply a centering to any View, including a Layout, by using the XML attribute android:layout_gravity". You probably want to give it the value "center".


2 Answers

In LinearLayout, use: android:layout_gravity="center".

In RelativeLayout, use: android:layout_centerInParent="true".

like image 60
Wroclai Avatar answered Sep 22 '22 12:09

Wroclai


If you are using a LinearLayout , use the gravity attribute :

<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:id="@+id/imageView1"         android:src="@drawable/icon"         android:layout_height="wrap_content"         android:scaleType="centerInside" /> </LinearLayout> 

If you are using a RelativeLayout , you can use android:layout_centerInParent as follows :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent" >      <ImageView android:id="@+id/imageView1"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:src="@drawable/icon"         android:scaleType="centerInside"         android:layout_centerInParent="true" />  </RelativeLayout> 
like image 22
Houcine Avatar answered Sep 22 '22 12:09

Houcine