如何在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>

其他回答

重新排列布局、图像或文本视图的位置属于对齐主题。因此,如果您想将图像src垂直放置在中间,应该使用下面编写的代码

android:layout_centerVertical="true"

和中心水平

android:layout_centerHorizontal="true"

否则,我认为我们也可以使用重力将每个元素放在父布局的中间,如android:gravity=“center”

如果您试图在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>

用于相对布局

android:layout_centerInParent="true"

以及其他布局

android:gravity="center" 
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:textStyle="bold"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Tours"
        android:id="@+id/textView" />

正如许多答案所表明的那样,上述工作正常。

android:gravity="center"

如果要使其垂直居中:

android:gravity="center_vertical"

或仅水平:

android:gravity="center_horizontal"