Sunday, 17 May 2015

Centering a button in android Linear and Relative Layouts

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 -
  1. Linear Layout and
  2. Relative Layout
Before we proceed to see how the actual layout files look like lets see the two layout view attributes that are commonly confused with -
  1. android:gravity and : Sets the gravity of the content of the View it's used on.
  2. android:layout_gravity  : Sets the gravity of the View or Layout relative to its parent.
So generally you can either put android:gravity="center" on the parent or android:layout_gravity="center" on the child.

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)
and layout should look like



 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 - 
  1. android:layout_centerInParent="true" (For centering in whole screen)
  2. android:layout_centerVertical="true" (For centering vertically)
  3. android:layout_centerHorizontal="true" (For centering vertically)
 Layouts will look same as the screenshots provided above for linear layout.

Related Links

No comments:

Post a Comment

t> UA-39527780-1 back to top