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


当前回答

在我看来,

android:gravity="center"

优于,

android:layout_centerInParent="true"

这比,

android:layout_centerHorizontal="true"
android:layout_centerVertical="true"

至少用于格式化文本。

其他回答

字体填充也会影响文本的位置,您可以通过添加includefontpadding=false来删除它

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

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

android:gravity=“中心”或

如果要水平或垂直居中

android:gravity=“center_horizontal”

android:gravity=“center_vertical”

试试看:

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

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

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

代码如下

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