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
?
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.
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.
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.
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
android:gravity="center"
This will do the trick
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With