Background
I have tried centering various views in Android and each time I end by with incorrect layouts. So in this post I am going to cover how to center a simple button in your layout. I will show this for both layouts -
- Linear Layout and
- Relative Layout
- android:gravity and : Sets the gravity of the content of the View it's used on.
- android:layout_gravity : Sets the gravity of the View or Layout relative to its parent.
Centering a Button in Linear Layout
For Linear layout you should use xml (button_linear.xml) that looks something like below -
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:orientation="vertical" > <Button android:id="@+id/centerButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> </LinearLayout>
This will place the button on the center of the screen. If you want to center it just vertically or horizontally you can use following values in android:gravity tag -
- center_vertical|center_horizontal or center (For centering in whole screen)
- center_vertical (For centering vertically)
- center_horizontal (For centering horizontally)
Now let's see the same in a Relative layout.
Centering a Button in Relative Layout
In Relative Layout the xml would be
<?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" android:orientation="vertical" > <Button android:id="@+id/centerButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Hello World!" /> </RelativeLayout>
Notice the android:layout_centerInParent attribute
This will put the button in the center of entire screen. Analogous to linear layout , attributes that can be used here are -
- android:layout_centerInParent="true" (For centering in whole screen)
- android:layout_centerVertical="true" (For centering vertically)
- android:layout_centerHorizontal="true" (For centering vertically)
Layouts will look same as the screenshots provided above for linear layout.
No comments:
Post a Comment