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?
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 .
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.
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".
In LinearLayout
, use: android:layout_gravity="center"
.
In RelativeLayout
, use: android:layout_centerInParent="true"
.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With