A small Android tip to show you how to center button on screen. Wrap button in RelativeLayout, and set following attributes to “true“.


android:layout_centerVertical="true"
android:layout_centerHorizontal="true"

Following is a full example to demonstrate the use of above tip to center a button on screen.

1. Android Layout

A button in layout.

File : res/layout/main.xml


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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       	android:layout_centerVertical="true"
       	android:layout_centerHorizontal="true"
        android:text="Button" />

</RelativeLayout>

2. Activity

Simple activity class, do nothing but display the above layout file.


package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;

public class HelloWorldActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

3. Demo

Start it, and see output :

center button on screen

Download Source Code

References

  1. Android RelativeLayout LayoutParams Javadoc