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


当前回答

让我们在屏幕中显示全文视图

 <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Hello World!"
    android:gravity="center"
    />

让我们说相对布局中的文本视图(未满)

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:layout_centerInParent=true
    />

假设Linear_layout中的Textview(未满)

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:layout_gravity="centre"
    />

其他回答

您可以使用android:gravity=“center”将文本视图居中

代码如下

    <TextView
     android:text="@string/yourText"
     android layout_height="wrap_content"
     android layout_height="wrap_content"
     android:gravity="center" />

通过.xml文件重力可以设置为中心,如下所示

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

通过java,以下是解决特定问题的方法

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

试试看:

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

文本视图宽度和高度应为match_parent,并在文本视图属性中添加android:gravity=“center”。

使用android:gravity=“center”解决问题。