Main Tutorials

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 Author

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

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Poipo
9 years ago

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

cracker
10 years ago

This was inadvertently typed.Ignore !

cracker
10 years ago

Kyong,

You could have used android:layout_centerInParent