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


当前回答

您可以使用android:gravity=“center”将文本视图居中

代码如下

    <TextView
     android:text="@string/yourText"
     android layout_height="wrap_content"
     android layout_height="wrap_content"
     android:gravity="center" />

其他回答

试试看:

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

<LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        android:layout_height="wrap_content">
    <TextView
            android:id="@+id/failresults"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:gravity="center_vertical|center_horizontal"
            android:text=""
            android:textSize="12sp" />
</LinearLayout>

如果在linearlayout中有文本视图,则需要将它们都设置为重心

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

最简单的方法(令人惊讶的是,只有在评论中才会提到,所以我才会发布答案)是:

textview.setGravity(Gravity.CENTER)

这是我在应用程序中使用的答案。它在屏幕中央显示文本。

<TextView
    android:id="@+id/txtSubject"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/subject"
    android:layout_margin="10dp"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge" />