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


当前回答

你可以为此改变android:重力。

android:gravity=“中心”或

如果要水平或垂直居中

android:gravity=“center_horizontal”

android:gravity=“center_vertical”

其他回答

只需将其添加到xml中。

android:gravity="center" 

必须这样设置“重力”:

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

在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
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" />

如果XML文件中只有一个TextView,则可以将父视图重心作为中心。这将使您的子元素位于屏幕的中心,然后您可以将您的子视图作为高度和宽度的环绕。