Android – How to center button on screen

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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Poipo
Guest
Poipo

How do I do that in linearlayout….???

cracker
Guest
cracker

This was inadvertently typed.Ignore !

cracker
Guest
cracker

Kyong,

You could have used android:layout_centerInParent

trackback
Android Tutorial

[…] Android – How to center button on screen […]