I am using a linear layout to display a pretty light initial screen. It has 1 button that is supposed to centre in the screen both horizontally and vertically. However no matter what I try to do the button will top align centre. I have included the XML below, can some one point me in the right direction?
<?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"> <ImageButton android:id="@+id/btnFindMe" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|center_horizontal" android:background="@drawable/findme"></ImageButton> </LinearLayout>
If you have a single Button in your Activity and you want to center it the simplest way is to use a RelativeLayout and set the android:layout_centerInParent=”true” property on the Button.
To center align LinearLayout, assign android:gravity attribute of this LinearLayout with the value “center”. Let us create an Android application with LinearLayout containing two Button widgets as children. We shall center align these children using gravity attribute.
We can align the buttons horizontally as well as vertically. We can center the button by using the following methods: text-align: center - By setting the value of text-align property of parent div tag to the center. margin: auto - By setting the value of margin property to auto.
Center using a LinearLayout:
<LinearLayout android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" > <ImageButton android:id="@+id/btnFindMe" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/findme" /> </LinearLayout>
If you want to center an item in the middle of the screen don't use a LinearLayout
as these are meant for displaying a number of items in a row.
Use a RelativeLayout
instead.
So replace:
android:layout_gravity="center_vertical|center_horizontal"
for the relevant RelativeLayout
option:
android:layout_centerInParent="true"
So your layout file will look like this:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout android:id="@+id/RelativeLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <ImageButton android:id="@+id/btnFindMe" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="@drawable/findme"></ImageButton> </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