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


当前回答

应用重力:

TextView txtView = (TextView) findViewById(R.id.txtView);
txtView.setGravity(Gravity.CENTER_HORIZONTAL);

对于垂直:

txtView.setGravity(Gravity.CENTER_VERTICAL);

在XML中:

<TextView      
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:gravity="center"
    android:text="@string/Hello_World"        
/>

其他回答

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

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

对于kotlin:

如果要将TextView从代码中居中:

textView.gravity = Gravity.CENTER

如果要水平居中:

textView.gravity = Gravity.CENTER_HORIZONTAL

或者,垂直居中:

textView.gravity = Gravity.CENTER_VERTICAL

您可以这样做以使文本居中

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

试试看:

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