Android 8.1(Oreo)中ConstraintLayout子布局重叠显示异常咨询
嘿,这个问题我之前也踩过坑!核心原因是你在ConstraintLayout里混用了RelativeLayout的专属布局属性,再加上Android 8.1对旧版ConstraintLayout的层级处理存在兼容性bug,才导致publisherViewContainer在8.1上被遮挡。下面是具体的修复方案:
1. 移除无效的RelativeLayout属性,改用ConstraintLayout标准约束
你给publisherViewContainer加了android:layout_alignParentBottom="true"——这是RelativeLayout的专属属性,在ConstraintLayout里属于无效属性,不同系统版本对这类无效属性的解析逻辑不一样,这就是8.1显示异常的主要诱因。
你已经用了ConstraintLayout的app:layout_constraintBottom_toBottomOf="parent"来定位底部,所以直接删掉android:layout_alignParentBottom="true"就好。
2. 强化视图层级控制,确保8.1上生效
虽然ConstraintLayout默认是XML中后声明的View层级更高,但结合elevation使用时,8.1上可能出现elevation不生效的情况。这里有两种可靠的解决方式:
方式一:用ConstraintLayout专属的layout_constraintZ属性(推荐)
如果你的项目用的是android.support.constraint:constraintlayout:1.1.0及以上版本,直接给publisherViewContainer加上app:layout_constraintZ="20dp",这个属性是ConstraintLayout专门用来控制Z轴层级的,比系统的android:elevation更适配ConstraintLayout的层级管理逻辑:
<RelativeLayout android:id="@+id/publisherViewContainer" android:layout_marginLeft="5dp" android:layout_marginBottom="5dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:layout_width="120dp" android:layout_height="90dp" android:elevation="20dp" app:layout_constraintZ="20dp" <!-- 新增这个属性 --> android:background="@color/colorPrimary"/>
方式二:确保视图声明顺序(基础方案)
如果不想升级ConstraintLayout版本,只要保证publisherViewContainer在XML里的声明顺序在subscriberViewContainer之后(你现在已经是这样),同时移除所有无效的RelativeLayout属性,让ConstraintLayout的默认层级规则正常生效就行。
3. 修复后的完整布局代码
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto"> <RelativeLayout android:id="@+id/subscriberViewContainer" android:layout_marginBottom="50dp" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:background="@color/colorAccent"/> <RelativeLayout android:id="@+id/publisherViewContainer" android:layout_marginLeft="5dp" android:layout_marginBottom="5dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:layout_width="120dp" android:layout_height="90dp" android:elevation="20dp" app:layout_constraintZ="20dp" android:background="@color/colorPrimary"/> </android.support.constraint.ConstraintLayout>
额外提示
如果你的项目还在使用旧版的android.support.constraint.ConstraintLayout,建议升级到AndroidX版本的androidx.constraintlayout:constraintlayout,新版本修复了大量旧版本的兼容性问题,包括8.1上的层级处理bug,能避免很多类似的坑。
内容的提问来源于stack exchange,提问作者Shahal

