How to align the text inside the TextView in Android?

AndroidTextviewAndroid Gui

Android Problem Overview


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

Android Solutions


Solution 1 - Android

Did you try the gravity attribute on the TextView ?

  android:gravity="center"

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

Solution 2 - Android

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

More information could be found here or here.

Solution 3 - Android

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

Solution 4 - Android

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"

Solution 5 - Android

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

Solution 6 - Android

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser552400View Question on Stackoverflow
Solution 1 - AndroidOvidiu LatcuView Answer on Stackoverflow
Solution 2 - AndroidbarrelView Answer on Stackoverflow
Solution 3 - AndroidBharat SinghView Answer on Stackoverflow
Solution 4 - AndroidZack AminView Answer on Stackoverflow
Solution 5 - AndroidPranav PView Answer on Stackoverflow
Solution 6 - AndroidSohail AnsariView Answer on Stackoverflow