要将文本放在Android设备屏幕的中间,你需要在你的XML布局中设置正确的属性。
在你的XML中设置什么属性取决于你在应用程序中使用什么视图类型。
本教程将帮助你学习如何在使用ConstraintLayout 、LinearLayout 、或RelativeLayout 视图时,将文本放在TextView 小组件的中央。
让我们先从ConstraintLayout 。
如何在Android中使用ConstraintLayout视图将文本居中
当你使用ConstraintLayout 视图创建一个活动时,你可以通过在TextView 的四边设置layout_constraint 属性,将你的TextView 小部件置于布局的中心。
这里有一个例子,一个TextView 在一个ConstraintLayout 的中心:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="Hello World!" />
</androidx.constraintlayout.widget.ConstraintLayout>
设置在四边的layout_constraint 属性将把TextView 小部件拉到布局的中心。
如何在Android中使用LinearLayout视图将文本居中
TextView 当你有一个LinearLayout 视图时,你可以通过将layout_width 和layout_height 属性设置为match_parent,将gravity 属性设置为center ,使TextView 小部件居中。
下面是一个XML布局的例子:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Hello World from Android" />
</LinearLayout>
你也可以通过使用layout_weight 属性使多个TextView 小部件居中。
下面的例子显示了如何将layout_weight 属性添加到每个TextView 小组件,并将其值设置为1 :
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Hello World from Android" />
<TextView
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Hello World from Android" />
</LinearLayout>
上面的代码将在布局内水平放置两个TextView 小部件。
如果你想让第一个TextView 小部件在第二个上面,你需要把LinearLayout 的orientation 设置为vertical :
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
现在你已经学会了如何在LinearLayout 视图中使文本居中。接下来让我们看看如何在RelativeLayout 视图中使文本居中。
如何在Android中使用相对布局视图将文本居中
要在RelativeLayout 视图中使文本居中,请按以下方法设置TextView 属性:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hello World from Android" />
</RelativeLayout>
layout_width 和layout_height 需要设置为wrap_content ,这样TextView 的大小与它的内容相匹配,而layout_centerInParent 将使TextView 小部件相对于父视图居中。
由于RelativeLayout 是用来显示相对位置的子视图的,所以对于将两个元素放在屏幕中心的位置来说,它并不理想。我建议你使用LinearLayout 视图来显示多个居中的子视图。
这就是你在开发Android应用程序时如何使文本居中的方法 😉