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


当前回答

对于文本的布局,最好使用

android:textAlignment=“中心”

对于对象等的其他布局,使用

android:gravity=“中心”

其他回答

还可以使用以下方法动态设置:

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

您可以将文本视图的重心设置为CENTER。

如果您正在使用RelativeLayout,请尝试在TextView标记中使用此属性:

android:layout_centerInParent= true

在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 height and width match_parent,则使用LinearLayout如果使用textview-height and width wrap_content,则可以将重力文本设置为居中,将文本对齐设置为水平居中,然后在LinearLayout中添加重力中心属性。

XML代码

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textAlignment="center"
    android:gravity="center"
    android:textColor="#000"
    android:textSize="30sp"
    android:text="Welcome to Android" />
    </LinearLayout>

Java代码

您可以通过编程这样做:-

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

非常感谢。