android - How do I center text horizontally and vertically in a TextView?

ID : 368

viewed : 128

Tags : androidtextviewandroid

Top 5 Answer for android - How do I center text horizontally and vertically in a TextView?

vote vote

92

I'm assuming you're using XML layout.

<TextView       android:layout_width="match_parent"      android:layout_height="match_parent"      android:gravity="center"     android:text="@string/**yourtextstring**" /> 

You can also use gravity center_vertical or center_horizontal according to your need.

As @stealthcopter commented, in java: .setGravity(Gravity.CENTER);.

And for Kotlin users, .gravity = Gravity.CENTER

vote vote

87

android:gravity="center"  

This will do the trick

vote vote

80

You can also set it up dynamically using:

textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); 
vote vote

61

android:layout_centerInParent="true" 

This works when used with a RelativeLayout where the layout's height & width are set to wrap_content.

vote vote

55

You can also use the combination:

android:gravity="left|center" 

Then, if textview width is more than "fill_parent" the text will still be aligned to left (not centered as with gravity set only to "center").

Top 3 video Explaining android - How do I center text horizontally and vertically in a TextView?

Related QUESTION?