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


Question

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?

1
1893
4/6/2018 2:40:14 PM

Accepted Answer

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.

and as @stealthcopter commented in java: .setGravity(Gravity.CENTER);

2909
7/10/2018 4:11:32 PM

android:gravity="center" 

This will do the trick


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon