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


当前回答

 <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:textAlignment=“中心”

对于对象等的其他布局,使用

android:gravity=“中心”

要在中心显示文本,请执行以下操作:

------------------>text<-------------------

使用以下样式:

<TextView  
    android:layout_width="match_parent" 
    android:layout_height="wrap_contect" 
    android:gravity="center"
    android:text="@string/text"
/>

android:gravity="center" 

你可以为此改变android:重力。

android:gravity=“中心”或

如果要水平或垂直居中

android:gravity=“center_horizontal”

android:gravity=“center_vertical”

使用android:gravity=“center”作为父对象

<LinearLayout
    android:layout_width="200dp"
    android:layout_height="200dp"

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

在任何视图的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" />