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


当前回答

在XML文件中使用。

布局文件

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

or:

在Java类中使用

TextView textView =(TextView)findViewById(R.id.texviewid);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

其他回答

对于kotlin:

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

textView.gravity = Gravity.CENTER

如果要水平居中:

textView.gravity = Gravity.CENTER_HORIZONTAL

或者,垂直居中:

textView.gravity = Gravity.CENTER_VERTICAL

这是我在应用程序中使用的答案。它在屏幕中央显示文本。

<TextView
    android:id="@+id/txtSubject"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/subject"
    android:layout_margin="10dp"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge" />
android:layout_centerInParent="true"

这在与RelativeLayout一起使用时有效,其中布局的高度和宽度设置为wrap_content。

应用重力:

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"        
/>

如果使用TableLayout,请确保将TableRows的重心也设置为中心。否则它将无法工作。至少在我将TableRow的重心设置为中心之前,它没有对我起作用。

例如,如下所示:

<TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center">        
    <TextView android:text="@string/chf" android:id="@+id/tv_chf" android:layout_weight="2" android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center"></TextView>        
</TableRow>