在 Android 中,要使控件在其父布局中上下居中(垂直居中),你可以使用不同的布局和属性来达到这个效果。以下是一些常见的方法:
- 使用
LinearLayout
和layout_gravity
:
如果你使用的是 LinearLayout
并且其方向是水平的(horizontal
),你可以通过设置子控件的 layout_gravity
属性为 center_vertical
来使其垂直居中。但是,如果 LinearLayout
的方向是垂直的(vertical
),那么这种方法将不起作用,因为 center_vertical
在垂直方向的 LinearLayout
中没有意义。
<LinearLayout | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:orientation="horizontal"> | |
<View | |
android:layout_width="wrap_content" | |
android:layout_height="wrap_content" | |
android:layout_gravity="center_vertical" /> | |
</LinearLayout> |
- 使用
RelativeLayout
和layout_centerVertical
:
在 RelativeLayout
中,你可以通过设置 layout_centerVertical
属性为 true
来使控件垂直居中。
<RelativeLayout | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content"> | |
<View | |
android:layout_width="wrap_content" | |
android:layout_height="wrap_content" | |
android:layout_centerVertical="true" /> | |
</RelativeLayout> |
- 使用
FrameLayout
和gravity
:
虽然 FrameLayout
主要是用来堆叠子控件的,但你可以通过设置其 gravity
属性为 center_vertical
来尝试使子控件垂直居中。然而,请注意,如果 FrameLayout
的高度是 wrap_content
,并且子控件没有填满整个 FrameLayout
,那么这种方法可能无法正确工作。
<FrameLayout | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:gravity="center_vertical"> | |
<View | |
android:layout_width="wrap_content" | |
android:layout_height="wrap_content" /> | |
</FrameLayout> |
- 使用
ConstraintLayout
:
ConstraintLayout
是一个非常强大且灵活的布局系统,你可以使用约束来精确定位控件。要使控件在 ConstraintLayout
中垂直居中,你可以将控件的顶部和底部都约束到其父布局的对应边,并设置适当的偏移量(如果需要)。
<androidx.constraintlayout.widget.ConstraintLayout | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content"> | |
<View | |
android:id="@+id/myView" | |
android:layout_width="wrap_content" | |
android:layout_height="wrap_content" | |
app:layout_constraintBottom_toBottomOf="parent" | |
app:layout_constraintTop_toTopOf="parent" | |
app:layout_constraintVertical_bias="0.5" /> | |
</androidx.constraintlayout.widget.ConstraintLayout> |
在上面的 ConstraintLayout
示例中,app:layout_constraintVertical_bias="0.5"
确保了 myView
在垂直方向上居中。