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


当前回答

android:gravity=“center_horizontal”表示文本水平居中。android:gravity=“center_vertical”用于垂直对齐文本中心。android:gravity=“center”用于垂直和水平对齐文本中心。

<TextView
        android:layout_width="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:layout_height="match_parent" />

其他回答

 <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>
android:layout_centerInParent="true"

这在与RelativeLayout一起使用时有效,其中布局的高度和宽度设置为wrap_content。

将布局文件中的重力属性设置为android:gravity=“中心”

android:gravity=“center_horizontal”表示文本水平居中。android:gravity=“center_vertical”用于垂直对齐文本中心。android:gravity=“center”用于垂直和水平对齐文本中心。

<TextView
        android:layout_width="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:layout_height="match_parent" />

您也可以使用以下组合:

android:gravity="left|center"

然后,如果文本视图宽度大于“fill_paint”,则文本仍将向左对齐(不居中,因为重力仅设置为“center”)。