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
If you use LinearLayout
you can add gravity center:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
/>
</LinearLayout>`
<?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="match_parent"
android:layout_height="wrap_content"
android:layout_gravity = "center"
android:background="@drawable/findme">
</ImageButton>
</LinearLayout>
The above code will work.
As per the Android documentation for XML Attributes of android:layout_gravity, we can do it easily :)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton android:id="@+id/btnFindMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/findme"></ImageButton>
</LinearLayout>
It would be easier to use relative layouts, but for linear layouts I usually center by making sure the width matches parent :
android:layout_width="match_parent"
and then just give margins to right and left accordingly.
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
use
android:layout_centerHorizontal="true"
This is working for me.
android:layout_alignParentEnd="true"