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

其他回答

通过.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);

我假设您使用的是XML布局。

<TextView  
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:gravity="center"
    android:text="@string/**yourtextstring**"
/>

还可以根据需要使用重力center_vertical或center_horizontal。

正如@steelthcopter在java:.setGravity(Gravity.CENTER);中评论的那样;。

对于Kotlin用户,.egravity=重力.CENTER

用于相对布局

android:layout_centerInParent="true"

以及其他布局

android:gravity="center" 

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

<TextView
    android:gravity="center" />

您需要像这样设置文本视图重力(水平居中和垂直居中):

android:layout_centerHorizontal="true"   

android:layout_centerVertical="true"

动态使用:

textview.setGravity(Gravity.CENTER);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);