Android Marshmallow及以下版本ConstraintLayout膨胀异常问题
解决Android Marshmallow及以下版本的ConstraintLayout InflateException问题
我之前也碰到过一模一样的情况——高版本系统跑起来顺风顺水,一到6.0及以下就直接炸锅,给你几个排查和解决的方向,亲测有用:
1. 检查ConstraintLayout依赖与项目配置的兼容性
你用的com.android.support.constraint:constraint-layout:1.1.0本身支持API 9+,但得确保项目配置跟它匹配:
- 打开Module级的
build.gradle,确认compileSdkVersion至少是26(这是ConstraintLayout 1.1.0推荐的编译SDK版本) - 同时检查
minSdkVersion是否设置正确,如果要兼容到Marshmallow(API 23),minSdkVersion得设为23或更低
2. 确保AppCompat库正确引入
低版本系统需要AppCompat的支持才能正常加载support库中的控件,在你的build.gradle里补上这个依赖:
implementation 'com.android.support:appcompat-v7:28.0.0'
注意版本要和ConstraintLayout统一,28.0.0是support库的最终稳定版,和1.1.x的ConstraintLayout适配性最好。
3. 排查布局XML的细节问题
你的布局根标签是android.support.constraint.ConstraintLayout,这里有几个容易踩坑的点:
- 必须完整添加命名空间,少了
xmlns:app会导致约束属性无法解析,直接触发Inflate失败:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent">
- 检查布局里有没有用API 24及以上才支持的属性,比如
android:foreground、android:foregroundGravity这类,低版本系统不认识这些属性,会直接崩在布局加载阶段 - 暂时把根布局的
wrap_content改成match_parent测试,低版本系统对ConstraintLayout的wrap_content解析偶尔会有bug
4. 清理缓存并重建项目
有时候缓存会搞出莫名其妙的问题,按这个流程走一遍:
- 点击Android Studio顶部的
Build->Clean Project - 接着点击
Build->Rebuild Project - 必要时可以手动删除项目根目录下的
.gradle和build文件夹,再重新同步项目
5. 升级ConstraintLayout到最新support版本
1.1.0是比较老的版本了,试试升级到1.1.3(support库的最终ConstraintLayout版本):
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
这个版本修复了不少低版本系统的兼容问题。
如果以上方法都没解决,建议把完整的布局代码或者Logcat里的详细崩溃栈贴出来,说不定是某个子View的属性导致的问题,能更精准定位。
内容的提问来源于stack exchange,提问作者Róbert Fodor
相关产品推荐
相关产品推荐

