70

In my app screen, i want to show Heading as horizontally center. I tried with below layout xml codes

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:layout_marginTop="10dip"
  >
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="Connections" />
</RelativeLayout>

thanks

Riskhan
  • 4,434
  • 12
  • 50
  • 76

6 Answers6

160

android:gravity controls the appearance within the TextView. So if you had two lines of text they would be centered within the bounds of the TextView. Try android:layout_centerHorizontal="true".

Brian Dupuis
  • 8,136
  • 3
  • 25
  • 29
  • 1
    Notice that this won't work if a RelativeLayout contains an attribute android:gravity="center_horizontal". – CoolMind Jan 16 '16 at 13:18
  • 6
    If this doesn't work, make sure that your text view's width is also set to `wrap_content` instead of `match_parent` – Munib Jul 17 '17 at 18:48
  • making the TextView width : wrap content , makes it invisible. – meekash55 Jan 20 '21 at 11:43
  • android:layout_centerHorizontal="true" android:gravity="center" I think it's correct. so that TextView will be centered in Layout, and text will be centered in TextView. – Venus Jun 22 '22 at 06:24
20

Use this:

android:layout_centerHorizontal="true"

within TextView

ViliusK
  • 11,345
  • 4
  • 67
  • 71
Akram
  • 7,548
  • 8
  • 45
  • 72
7
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:layout_marginTop="10dip"
    >
  <TextView
    android:layout_centerHorizontal="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Connections" />
</RelativeLayout>
5

use layout_centerInParent="true"(layout_centerInHorizontal,layout_centerInVertical)

gravity means the algin of text on textview, not the view itself

JohnCookie
  • 661
  • 3
  • 7
4

replace textview with below code

<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:text="Connections" />
SathishBabu S
  • 382
  • 3
  • 11
3

only add this android:gravity="center_horizontal"

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:layout_marginTop="10dip" 
  android:gravity="center_horizontal"
  >
  <TextView

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="Connections" />
</RelativeLayout>
Parag Chauhan
  • 35,760
  • 13
  • 86
  • 95