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


当前回答

让我们在屏幕中显示全文视图

 <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Hello World!"
    android:gravity="center"
    />

让我们说相对布局中的文本视图(未满)

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:layout_centerInParent=true
    />

假设Linear_layout中的Textview(未满)

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:layout_gravity="centre"
    />

其他回答

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

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

我假设您使用的是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.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>

试试这种方法,它会奏效的

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center">
  
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="center"/>

</LinearLayout>

试试看:

如果使用textview height and width match_parent,则使用LinearLayout如果使用textview-height and width wrap_content,则可以将重力文本设置为居中,将文本对齐设置为水平居中,然后在LinearLayout中添加重力中心属性。

XML代码

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textAlignment="center"
    android:gravity="center"
    android:textColor="#000"
    android:textSize="30sp"
    android:text="Welcome to Android" />
    </LinearLayout>

Java代码

您可以通过编程这样做:-

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

非常感谢。