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


当前回答

试试看:

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

使用下面的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>

我不认为,你真的需要这样做,只需像这样在布局文件中定义你的TextView

<RelativeLayout
    android:layout_width="width"
    android:layout_height="height">
    <TextView
        android:id="@+id/yourid"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your text" />
</RelativeLayout>

我添加了xml片段,以使文本视图中心在线性和相对布局中对齐。

在线性布局中

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text In Center"
android:layout_gravity="center"
android:gravity="center"/>

在相对布局中

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Text In Center"
android:layout_centerInParent= true/>

让我们在屏幕中显示全文视图

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

让我们说相对布局中的文本视图(未满)

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:layout_centerInParent=true
    />

假设Linear_layout中的Textview(未满)

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:layout_gravity="centre"
    />