64

I have a multiline TextView in Android. It is a child of a LinearLayout. It is already centered horizontally and I also want to have the text inside it centered.

Here's what I have now:

_ _ _ _ _ _| aaaaaaaaaaaaaaaaaaaaa  
_ _ _ _ _ _| aaaaaaaa  
_ _ _ _ _ _| aaaaaaaaaaaaaa

What I want is:

_ _ _ _ _ _| aaaaaaaaaaaaaaaaaaaaa  
_ _ _ _ _ _|       aaaaaaaa  
_ _ _ _ _ _|     aaaaaaaaaaaaaa

Where:

_ _ _ _ = the space on the side of the TextView

| = the TextView edge

Lupu Silviu
  • 1,125
  • 11
  • 22

6 Answers6

173

Did you try the gravity attribute on the TextView ?

  android:gravity="center"

And make sure to use android:gravity and not android:layout_gravity.

Alexander Pacha
  • 8,494
  • 3
  • 64
  • 100
Ovidiu Latcu
  • 70,421
  • 14
  • 74
  • 84
15

android:gravity="center_horizontal" should do the trick.

More information could be found here or here.

030
  • 9,351
  • 10
  • 70
  • 110
barrel
  • 974
  • 7
  • 15
2

Yes, use android:gravity attribute to change the position of data inside views.

2

The gravity attribute is the update to Alignment. Gravity is available in the attributes inspector as well as being able to do;

android:gravity="center"
Zack Amin
  • 312
  • 2
  • 10
1

If you just want to align your text in textView then textAlignment is better option then gravity.

Add android:textAlignment="center" for Center

Add android:textAlignment="textStart" for Left

Add android:textAlignment="textEnd" for Right

Pranav P
  • 1,865
  • 18
  • 37
-1

Make the text (which you want to set into TextView) in strings.xml as following :

<string name="content">
<center>Your text goes here.</center>
</string>

and in TextView add following attribute:

<TextView
...
android:text="@string/content"/>

It will center the text into TextView horizontally.

Sohail Ansari
  • 81
  • 1
  • 5