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


当前回答

要在中心显示文本,请执行以下操作:

------------------>text<-------------------

使用以下样式:

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

android:gravity="center" 

其他回答

如果TextView的高度和宽度是换行内容,则TextView中的文本始终居中。但如果TextView的宽度为match_parent,高度为match-parent或wrap_content,则必须编写以下代码:

对于RelativeLayout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</RelativeLayout>

对于LinearLayout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</LinearLayout>
 <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="@string/**yourtextstring**"
/>

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

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

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

我不认为,你真的需要这样做,只需像这样在布局文件中定义你的TextView

<RelativeLayout
    android:layout_width="width"
    android:layout_height="height">
    <TextView
        android:id="@+id/yourid"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your text" />
</RelativeLayout>

使用android:gravity=“center”解决问题。