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


当前回答

在对TextView使用gravity时,API级别17中实现了另一种方法-

textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

不知道有什么区别,但它也起作用。但仅适用于API 17级或更高级别。

其他回答

如果您试图在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>

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

我添加了xml片段,以使文本视图中心在线性和相对布局中对齐。

在线性布局中

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text In Center"
android:layout_gravity="center"
android:gravity="center"/>

在相对布局中

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Text In Center"
android:layout_centerInParent= true/>

字体填充也会影响文本的位置,您可以通过添加includefontpadding=false来删除它

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

使用android:textAlignment=“center”

       <TextView
        android:text="HOW WAS\nYOUR\nDAY?"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:id="@+id/textView5"
         />