如何解决Android Studio中Lottie XML代码出现空引用报错的问题?
Lottie XML空报错问题解决方法
可按照以下步骤依次排查修复:
- 校验动画资源合法性
确认res/raw目录下的animation文件是未损坏的标准Lottie JSON文件,没有内容为空、后缀被误改、文件导出不完整的问题,这是触发XML加载空报错最常见的原因。 - 补充布局兼容配置
首先确认布局根节点已经声明了app命名空间xmlns:app="http://schemas.android.com/apk/res-auto",未声明命名空间会导致自定义属性不生效,触发加载错误。之后可以在LottieAnimationView的配置中增加渲染质量配置,降低加载失败概率,修改后的布局代码如下:<com.airbnb.lottie.LottieAnimationView android:id="@+id/animationView" android:layout_width="match_parent" android:layout_height="wrap_content" app:lottie_rawRes="@raw/animation" app:lottie_autoPlay="true" app:lottie_loop="true" app:lottie_preferredQuality="low"/> - 适配依赖版本
3.4.0版本Lottie要求项目compileSdkVersion≥ 29,如果你的项目compileSdk版本低于该要求,可以降级到2.8.0稳定版,修改gradle依赖为:implementation "com.airbnb.android:lottie:2.8.0" - 增加代码兜底逻辑
在页面初始化时对动画加载逻辑加异常捕获,避免加载失败直接崩溃,参考代码如下:try { animationView.setAnimation(R.raw.animation) animationView.playAnimation() } catch (e: Exception) { // 加载失败兜底:隐藏动画、展示静态占位图 animationView.visibility = View.GONE }
对应报错截图:
内容的提问来源于stack exchange,提问作者Alam merdeka
相关产品推荐
相关产品推荐

