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


当前回答

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

其他回答

<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:layout_centerInParent="true"

以及其他布局

android:gravity="center" 

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

最简单的方法(令人惊讶的是,只有在评论中才会提到,所以我才会发布答案)是:

textview.setGravity(Gravity.CENTER)

还可以使用以下方法动态设置:

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