如何在TextView中水平和垂直居中文本,以便它正好出现在Android中的TextView的中间?


当前回答

只需将其添加到xml中。

android:gravity="center" 

其他回答

文本视图宽度和高度应为match_parent,并在文本视图属性中添加android:gravity=“center”。

你试过这样吗?

<TextView
android:id="+@id/txtVw"
android:gravity="center"
/>

如果TextView的高度和宽度是换行内容,则TextView中的文本始终居中。但如果TextView的宽度为match_parent,高度为match-parent或wrap_content,则必须编写以下代码:

对于RelativeLayout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" 
        android:text="Hello World" />

</RelativeLayout>

对于LinearLayout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Hello World" />

</LinearLayout>
<TextView
android:id="+@id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
/>
android:gravity="center" 

这就行了