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


当前回答

试试看:

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

其他回答

试试看:

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

在RelativeLayout中,它会很好。

还有另一个按钮和任何你可以添加的东西。

以下内容对我很有用。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ff314859"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">
    <TextView 
        android:id="@+id/txt_logo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="your text here"
        android:textSize="30dp"
        android:gravity="center"/>

        ...other button or anything else...

</RelativeLayout>

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

textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

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

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

android:gravity="center"

如果要使其垂直居中:

android:gravity="center_vertical"

或仅水平:

android:gravity="center_horizontal"
There are 2 ways to do this :

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

2. From Java class
    use : 

     [textview].setGravity(Gravity.CENTER);