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


当前回答

您可以这样做以使文本居中

<TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        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);

使用android:gravity=“center”作为父对象

<LinearLayout
    android:layout_width="200dp"
    android:layout_height="200dp"

    android:gravity="center"
    >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Hello world"
        />
</LinearLayout>

如果要将文本视图的宽度和高度设置为环绕内容,则必须根据父级支持的属性通过布局重力来管理其位置。否则你可以做。

<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"
/>

您可以这样做以使文本居中

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