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


当前回答

android:textAlignment="center"

这就行了

其他回答

您需要像这样设置文本视图重力(水平居中和垂直居中):

android:layout_centerHorizontal="true"   

android:layout_centerVertical="true"

动态使用:

textview.setGravity(Gravity.CENTER);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

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

在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);

将布局文件中的重力属性设置为android:gravity=“中心”

如果您正在使用RelativeLayout,请尝试在TextView标记中使用此属性:

android:layout_centerInParent= true