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


当前回答

如果您试图在TableLayout中的TableRow上居中文本,以下是我实现这一点的方法:

<TableRow android:id="@+id/rowName"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:padding="5dip" >
    <TextView android:id="@+id/lblSomeLabel"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:gravity="center"
              android:layout_width="0dp"
              android:layout_weight="100"
              android:text="Your Text Here" />
</TableRow>

其他回答

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

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

       <TextView
        android:text="HOW WAS\nYOUR\nDAY?"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:id="@+id/textView5"
         />

对于kotlin:

如果要将TextView从代码中居中:

textView.gravity = Gravity.CENTER

如果要水平居中:

textView.gravity = Gravity.CENTER_HORIZONTAL

或者,垂直居中:

textView.gravity = Gravity.CENTER_VERTICAL

您可以在java中用程序实现这一点:textview.setGravity(Gravity.CENTER);