Android Layout | How to Center Text & View “TextView” Horizontally and Vertically

How to center a view or its content e.g. TextView or Button horizontally and vertically? layout_gravity can be used to position a view in the center of its parent. While gravity attribute is used to position view’s content e.g. “text” in the center of the view.

 ( 1 ) Center TextView Horizontally

android:layout_gravity=”center_horizontal”

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
       android:orientation="vertical"
       android:layout_margin="10dp"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_gravity="center"
        android:background="#333"
        android:textColor="#fff"
        />

</LinearLayout>

( 2 ) Center TextView Vertically

android:layout_gravity=”center_vertical” dose not work!!

To center TextView vertically, you need to make a trick. Place TextView inside a RelativeLayout then set the TextView attribute android:layout_centerInParent=”true”

android-vertical-center

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
       android:orientation="vertical"
       android:layout_margin="10dp"
    tools:context=".MainActivity" >
   
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_centerInParent="true"
        android:layout_gravity="center_vertical"
        android:gravity="center"
        android:background="#333"
        android:textColor="#fff"
        />
    
</RelativeLayout>

 

( 3 ) Center Text Horizontally

android:gravity=”center_horizontal”

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:gravity="center"
        android:background="#333"
        android:textColor="#fff"
        />

( 4 ) Center Text Horizontally & Vertically

android:gravity=”center” this will center the text horizontally and vertically

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:text="Hello World!"
        android:gravity="center"
        android:background="#333"
        android:textColor="#fff"
        />