How to align the text inside the TextView in Android?
Asked Answered
P

6

66

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

Particolored answered 19/6, 2012 at 7:13 Comment(4)
See detail explanation of gravity https://mcmap.net/q/115769/-right-align-text-in-android-textviewCede
Use android:textAlignment="center" see the detail solution here https://mcmap.net/q/40537/-how-do-i-center-text-horizontally-and-vertically-in-a-textviewTumbler
Why do I feel that @Chathura Wijesinghe answered the real question? Got my upvote!Maun
unfortunately, it was deleted by @bhargav-rao . the same solution I used for most off the apps.Tumbler
Z
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.

Zared answered 19/6, 2012 at 7:15 Comment(3)
Make sure to use android:gravity and not android:layout_gravity. This just cost me 30 min.Executory
Thank you very much @AlexanderPacha This should be added to the answer as I also got confusedMow
Miraculous! I wonder what the heck android:textAlignment is supposed to do? But not enough to actually dig for it. This works!Banta
A
15

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

More information could be found here or here.

Auspex answered 19/6, 2012 at 7:16 Comment(0)
I
3

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

Insignia answered 7/6, 2017 at 13:15 Comment(0)
S
3

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"
Supernumerary answered 14/9, 2020 at 13:29 Comment(0)
P
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

Polonaise answered 28/7, 2021 at 9:42 Comment(0)
S
-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.

Slavophile answered 13/8, 2018 at 14:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.