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


当前回答

如果TextView没有将height/width属性设置为wrap_content,请使用android:gravity=“center”。但有些人抱怨说,使用这种方法行不通。这是因为它们的布局没有相同的重力。您可以设置

android:layout_gravity=“center”在文本视图中(这仅适用于文本视图)

or

android:gravity=“center”在父布局中(这将适用于其中的所有视图)

其他回答

试试看:

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" />
There are 2 ways to do this :

1. From Xml
     use :  
        <TextView
         .........
        android:gravity="center"/>

2. From Java class
    use : 

     [textview].setGravity(Gravity.CENTER);

如果使用TableLayout,请确保将TableRows的重心也设置为中心。否则它将无法工作。至少在我将TableRow的重心设置为中心之前,它没有对我起作用。

例如,如下所示:

<TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center">        
    <TextView android:text="@string/chf" android:id="@+id/tv_chf" android:layout_weight="2" android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center"></TextView>        
</TableRow>
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>