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


当前回答

简单地,在XML文件中,将文本视图重心设置为中心:

<TextView
    android:gravity="center" />

其他回答

 <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>

在RelativeLayout中,它会很好。

还有另一个按钮和任何你可以添加的东西。

以下内容对我很有用。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ff314859"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">
    <TextView 
        android:id="@+id/txt_logo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="your text here"
        android:textSize="30dp"
        android:gravity="center"/>

        ...other button or anything else...

</RelativeLayout>

对于那些想知道如何在其TextView元素中垂直居中,同时将其保持在左侧(水平)的人:

android:gravity="center"
android:textAlignment="viewStart"

在对TextView使用gravity时,API级别17中实现了另一种方法-

textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

不知道有什么区别,但它也起作用。但仅适用于API 17级或更高级别。

如果使用的是相对布局:

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/stringname"
    android:layout_centerInParent="true"/>

如果使用LinearLayout

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/stringname"
    android:layout_gravity="center"/>