将ConstraintLayout从1.0.2升级至1.1.0时出现Guideline.getAnchor错误
解决ConstraintLayout 1.1.0升级后出现的AssertionError: TOP错误
这个问题我之前帮不少开发者排查过,本质是ConstraintLayout 1.1.0版本对Guideline的属性校验变得更严格,你的布局里大概率存在Guideline类型和约束属性不匹配的情况。下面是具体的解决步骤:
1. 检查布局中的Guideline配置
首先打开报错相关的XML布局文件,找到所有<android.support.constraint.Guideline>标签,重点核对两个核心点:
- 确认Guideline的
android:orientation属性:- 垂直Guideline(
orientation="vertical")只能用水平方向相关约束,比如app:layout_constraintGuide_start、app:layout_constraintGuide_end、app:layout_constraintGuide_left、app:layout_constraintGuide_right - 水平Guideline(
orientation="horizontal")只能用垂直方向相关约束,比如app:layout_constraintGuide_top、app:layout_constraintGuide_bottom、app:layout_constraintGuide_percent(这个属性通用)
- 垂直Guideline(
- 如果你给垂直Guideline设置了
layout_constraintGuide_top这类垂直属性,或者给水平Guideline设置了layout_constraintGuide_left这类水平属性,就会触发这个断言错误。
举个错误示例:
<!-- 垂直Guideline错误绑定了top属性 --> <android.support.constraint.Guideline android:id="@+id/guideline_vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintGuide_top="16dp" />
修正后的正确写法:
<android.support.constraint.Guideline android:id="@+id/guideline_vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintGuide_start="16dp" />
2. 清理项目缓存并重建
旧版本的编译缓存可能会干扰新版本的逻辑,执行以下操作:
- 点击Android Studio顶部菜单栏的
Build→Clean Project - 接着点击
Build→Rebuild Project - 必要时可以手动删除项目根目录下的
.gradle文件夹和模块内的build文件夹,再重新构建
3. 升级到更高版本的ConstraintLayout
1.1.0版本确实存在一些已知的小bug,如果你不想修改布局代码,可以尝试升级到更稳定的版本(注意保持support库版本一致):
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
如果你的项目已经迁移到AndroidX,也可以直接使用AndroidX版本的ConstraintLayout:
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
4. 排查嵌套ConstraintLayout的问题
如果布局中存在嵌套的ConstraintLayout,里面的Guideline也可能出现属性不匹配的情况,需要逐一检查所有Guideline的配置。
按照上述步骤排查后,这个断言错误基本就能解决了。
内容的提问来源于stack exchange,提问作者Subin Babu
相关产品推荐
相关产品推荐

