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


当前回答

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

textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

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

其他回答

通过.xml文件重力可以设置为中心,如下所示

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

通过java,以下是解决特定问题的方法

textView1.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

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

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

使用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"
         />
 <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=“中心”