Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I center the text horizontally and vertically in a TextView, so that it appears exactly in the middle of the TextView in Android?

like image 734
pupeno Avatar asked Jan 11 '09 00:01

pupeno


People also ask

How do you center text in a TextView?

android:gravity="center" for text center in TextView. android:gravity="center_horizontal" inner text if you want horizontally centered. android:gravity="center_vertical" inner text if you want vertically centered. android:layout_centerInParent="true" if you want TextView in center position of parent view.

How do I center a textbox in android Studio?

android:gravity="center_horizontal" for align text Center horizontally. android:gravity="center_vertical" for align text Center vertically. android:gravity="center" for align text Center both vertically and horizontally.

How can I center text programmatically in android?

To center align text in TextView in Kotlin Android, set android:textAlignment attribute with the value “center” in layout file, or programmatically set the textAlignment property of the TextView object with View. TEXT_ALIGNMENT_CENTER in activity file.


2 Answers

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

like image 117
Bill Avatar answered Oct 29 '22 03:10

Bill


android:gravity="center"  

This will do the trick

like image 32
Jean Avatar answered Oct 29 '22 03:10

Jean