65

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,145
  • 11
  • 23

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
  • 9,187
  • 3
  • 68
  • 108
Ovidiu Latcu
  • 71,607
  • 15
  • 76
  • 84
15

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

More information could be found here or here.

030
  • 10,842
  • 12
  • 78
  • 123
barrel
  • 974
  • 7
  • 16
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
  • 514
  • 4
  • 12
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,755
  • 19
  • 39
-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
  • 131
  • 1
  • 6