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


当前回答

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

其他回答

我不认为,你真的需要这样做,只需像这样在布局文件中定义你的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>

必须这样设置“重力”:

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

如果使用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”解决问题。

正如许多答案所表明的那样,上述工作正常。

android:gravity="center"

如果要使其垂直居中:

android:gravity="center_vertical"

或仅水平:

android:gravity="center_horizontal"