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


当前回答

你试过这样吗?

<TextView
android:id="+@id/txtVw"
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>

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

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

有两种方法可以做到这一点。

XML代码中的第一个。您需要注意重力属性。您也可以在图形编辑器中找到该属性;它可能比XML编辑器更容易。

<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:gravity="center_vertical|center_horizontal"
    android:text="Your Text"
/>

对于您的特定场景,重力值为:

center_vertical|center_horizontal

在图形编辑器中,您可以找到所有可能的值,甚至可以看到它们的结果。