Contrary to what you might think, in a LinearLayout, match_parent
does not make it occupy all parent . The old name, fill_parent
, in that sense, was even worse.
Therefore, and wanting to use the android:layout_gravity
attribute, you must include the Button between two "auxiliary" views with a layout_weight
to indicate that they must occupy all available space above and below the Button.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Space
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:text="ok"
android:layout_gravity="center_horizontal"
/>
<Space
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
However this effect is easier to achieve using a RelativeLayout with android:layout_centerInParent="true"
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_centerInParent="true"
android:text="ok" />
</RelativeLayout>