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


当前回答

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

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

其他回答

<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
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center" />
android:textAlignment="center"

这就行了

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

android:layout_centerHorizontal="true"   

android:layout_centerVertical="true"

动态使用:

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

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