Contrary to popular belief, a Linearlayout, match_parent
does not make it occupy all the Parent. The old name, fill_parent
, in that sense, it was even worse.
So being and wanting to use the attribute android:layout_gravity
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>
Are you using Linearlayout? Put the whole layout to make sure what the problem is.
– Pablo Almeida
Related: Position button at the bottom of the layout.
– ramaral