How to center a Button in an Android Layout?

In my last Android Training several people asked how they could center a single view, e.g. a Button, so I assume it is worth a short blog entry.

If you have a single Button in your Activity and you want to center it the simplest way is to use a RelativeLayout and set the android:layout_centerInParent=”true” property on the Button.

For example like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/captureFront"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="onClick"
        android:text="Make Photo" />

</RelativeLayout>

Alternative you can do this via a LinearLayout (thanks to Ravi Tamada via Twitter for the tip.

<?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:orientation="vertical" 
    android:gravity="center"
    >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello" 
        />

</LinearLayout>

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of vogella.com. With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Android and tagged , . Bookmark the permalink.