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


当前回答

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

<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" />

其他回答

在任何视图的ConstraintLayout中:

(使用约束布局时,将高度和宽度设置为0,并让约束管理视图边界。)

<View
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

我添加了xml片段,以使文本视图中心在线性和相对布局中对齐。

在线性布局中

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text In Center"
android:layout_gravity="center"
android:gravity="center"/>

在相对布局中

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Text In Center"
android:layout_centerInParent= true/>

如果XML文件中只有一个TextView,则可以将父视图重心作为中心。这将使您的子元素位于屏幕的中心,然后您可以将您的子视图作为高度和宽度的环绕。

您可以使用android:gravity=“center”将文本视图居中

代码如下

    <TextView
     android:text="@string/yourText"
     android layout_height="wrap_content"
     android layout_height="wrap_content"
     android:gravity="center" />
 <android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">


       <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="HELLO"
            android:textColor="@color/colorPrimaryDark"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>

 </android.support.constraint.ConstraintLayout>