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


当前回答

您可以将重力设置为垂直居中,将文本对齐设置为居中。

<TextView
     android:text="@string/yourText"
     android layout_height="wrap_content"
     android layout_height="wrap_content"
     android:gravity="center_vertical"
     android:textAlignment="center" />

其他回答

您可以这样做以使文本居中

<TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center" />
android:gravity="center" 

这就行了

这是我在应用程序中使用的答案。它在屏幕中央显示文本。

<TextView
    android:id="@+id/txtSubject"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/subject"
    android:layout_margin="10dp"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge" />

使用下面的xml代码,它对我有用,你可以改变它在中心的方向

<LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:background="@color/colorPrimaryDark"
        android:gravity="center"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/id_text"
            android:layout_width="wrap_content"
            android:textSize="18sp"
            android:textColor="@android:color/white"
            android:textStyle="normal"
            android:layout_height="wrap_content"
            android:text="centre me"/>
    </LinearLayout>

使用android:gravity=“center”解决问题。