如何在 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?

转载于:https://stackoverflow.com/questions/432037/how-do-i-center-text-horizontally-and-vertically-in-a-textview

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);

You can also set it up dynamically using:

textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
android:gravity="center" 

This will do the trick

android:layout_centerInParent="true"

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