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


当前回答

如果您试图在TableLayout中的TableRow上居中文本,以下是我实现这一点的方法:

<TableRow android:id="@+id/rowName"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:padding="5dip" >
    <TextView android:id="@+id/lblSomeLabel"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:gravity="center"
              android:layout_width="0dp"
              android:layout_weight="100"
              android:text="Your Text Here" />
</TableRow>

其他回答

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

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

or

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

android:layout_centerInParent="true"

这在与RelativeLayout一起使用时有效,其中布局的高度和宽度设置为wrap_content。

如果使用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:layout_centerInParent="true"

以及其他布局

android:gravity="center" 
android:gravity="center" 

这就行了