ConstraintLayout中是否需指定视图层级?XML顺序影响层级吗?
Android ConstraintLayout 视图层级规则解析
示例布局代码
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <View android:id="@+id/view1" android:layout_width="0dp" android:layout_height="0dp" android:background="@color/blue" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> <View android:id="@+id/view2" android:layout_width="0dp" android:layout_height="0dp" android:background="@color/black" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
问题描述
最终仅显示黑色的view2,因为它在视图层级上位于蓝色view1的上层。我的问题是:是否需要通过属性指定视图的上下层级,还是XML中的元素顺序就已决定了层级?我发现XML中靠后的元素反而在视图上层,这点有些困惑。
解答
- XML元素顺序默认决定视图层级:在Android所有ViewGroup(包括ConstraintLayout)中,XML里声明位置越靠后的视图,默认会被绘制在更上层。这是Android视图系统的通用规则,不是ConstraintLayout独有的特性,所以你会看到view2覆盖view1的现象。
- 支持手动调整层级:如果需要打破XML顺序的默认层级,可以通过以下方式调整:
- 使用
android:elevation属性(API 21及以上):数值越大的视图层级越高,还会附带阴影效果; - 使用
android:translationZ属性:仅调整Z轴顺序,不会添加阴影; - 代码动态调整:调用
View.bringToFront()或者ViewGroup.bringChildToFront(View)方法,将目标视图移到层级最上层。
- 使用
内容的提问来源于stack exchange,提问作者Lechius
相关产品推荐
相关产品推荐

