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


当前回答

迟到的GUI荣誉奖

我想为这个已经非常棒的线程增加一些价值。最后,在11年后,我们现在有了一种方法,可以从工具箱中拖放TextView,并通过GUI的财产框选择重力。幸运的是,GUI将财产简洁地组合为“center_vertical | center_horizontal”。

    <TextView
    android:text="This is my sample text."
    android:layout_width="match_parent"
    android:layout_height="35.7dp"
    android:id="@+id/textView2"
    android:layout_marginBottom="24.7dp"
    android:typeface="sans"
    android:textSize="20"
    android:gravity="center_vertical|center_horizontal" />

其他回答

如果要将文本视图的宽度和高度设置为环绕内容,则必须根据父级支持的属性通过布局重力来管理其位置。否则你可以做。

<TextView  
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:gravity="center"/> 

试试看:

如果使用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);

非常感谢。

我添加了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:gravity="center"
android:text="In the center"/>

以上是使用.xml文件进行设置。

但我更喜欢java版本,因为如果需要,您也可以在运行状态下在代码中禁用它。下面是java代码。

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

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

android:textAlignment=“中心”

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

android:gravity=“中心”