By Alvin Alexander. Last updated: August 12, 2018
I was just working on centering some components in an Android LinearLayout
and came upon this helpful advice:
android:gravity takes care of its children,
android:layout_gravity takes care of itself
So, in my case, where I wanted to center two buttons horizontally in a LinearLayout
, I used android:gravity="center"
.
In total, all of my code for this particular layout looks like this:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" style="@style/AppTheme"> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/imagesGridView" android:layout_width="match_parent" android:layout_height="wrap_content" android:columnWidth="120dp" android:numColumns="auto_fit" android:stretchMode="columnWidth" android:clickable="true" android:fadeScrollbars="true"> </GridView> <android.support.v7.widget.Toolbar android:id="@+id/imagesGridToolbar" android:minHeight="@dimen/abc_action_bar_default_height_material" android:background="#e9111111" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" xmlns:android="http://schemas.android.com/apk/res/android"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:gravity="center"> <Button android:id="@+id/cancelDeleteProcessButton" android:text="Cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#c0c0c0" android:layout_alignBottom="@+id/imagesGridView" android:layout_marginRight="32dp"/> <Button android:id="@+id/deleteImagesButton" android:text="Delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#c0c0c0" android:layout_alignBottom="@+id/imagesGridView" android:layout_toRightOf="@+id/cancelButton" android:layout_toEndOf="@+id/cancelButton"/> </LinearLayout> </android.support.v7.widget.Toolbar> </RelativeLayout>
I highlighted the gravity
piece of that code, and also highlighted the layout_marginRight
specification, which provides some separation between my two buttons.
In summary, if you needed to see how to center components in an Android LinearLayout
, I hope this was helpful.