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


当前回答

使用下面的xml代码,它对我有用,你可以改变它在中心的方向

<LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:background="@color/colorPrimaryDark"
        android:gravity="center"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/id_text"
            android:layout_width="wrap_content"
            android:textSize="18sp"
            android:textColor="@android:color/white"
            android:textStyle="normal"
            android:layout_height="wrap_content"
            android:text="centre me"/>
    </LinearLayout>

其他回答

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

如果TextView的高度和宽度是换行内容,则TextView中的文本始终居中。但如果TextView的宽度为match_parent,高度为match-parent或wrap_content,则必须编写以下代码:

对于RelativeLayout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</RelativeLayout>

对于LinearLayout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</LinearLayout>

TextView的高度和宽度是换行内容,然后文本视图中的文本始终居中,然后使用以下命令在父布局中居中:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Hello.."/>
</RelativeLayout>

对于LinearLayout,代码也相同:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello.."/>
</LinearLayout>

从语法上讲,父级是RelativeLayout java代码,这在运行时使用类似的代码

TextView textView1 =(TextView)findViewById(R.id.texView1);
RelativeLayout.LayoutParams layoutParams = RelativeLayout.LayoutParams)textView1.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
textView1.setLayoutParams(layoutParams);
android:gravity="center" 

这就行了

对于那些想知道如何在其TextView元素中垂直居中,同时将其保持在左侧(水平)的人:

android:gravity="center"
android:textAlignment="viewStart"