You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VectorDrawable在Android 5.0.1(Lollipop)中致应用崩溃求助

解决VectorDrawable选择器导致的Resources$NotFoundException崩溃问题

这个错误里出现的$ic_lose_weight_icon__0.xml是编译过程中生成的临时资源文件,报错说明系统找不到它,本质是你的VectorDrawable或其关联的状态选择器配置出了问题。下面是一步步的解决思路:

1. 检查VectorDrawable内的颜色引用是否合法

从你给出的代码片段看,你用了aapt命名空间,应该是在VectorDrawable里给路径设置了带状态的颜色。如果是这种情况,要确保:

  • 你引用的颜色状态列表(ColorStateList)确实存在于res/color/目录下,比如如果写了android:fillColor="@color/weight_icon_color_selector",那res/color/weight_icon_color_selector.xml必须是有效的状态颜色配置。
  • 不要在VectorDrawable内部直接嵌套复杂的状态逻辑,更稳妥的方式是用StateListDrawable包裹不同状态的VectorDrawable,而不是在单个vector里处理颜色状态。

举个正确的StateListDrawable示例(命名为ic_lose_weight_selector.xml放在res/drawable/):

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_lose_weight_icon_selected" android:state_active="true"/>
    <item android:drawable="@drawable/ic_lose_weight_icon_normal"/>
</selector>

这里的ic_lose_weight_icon_selected和ic_lose_weight_icon_normal是两个独立的VectorDrawable,分别对应选中和默认状态的样式。

2. 确保Gradle配置支持VectorDrawable

在你的app模块build.gradle文件中,添加VectorDrawable支持库的配置,避免版本兼容问题:

android {
    defaultConfig {
        // 启用VectorDrawable支持库
        vectorDrawables.useSupportLibrary = true
    }
}

同时确保你依赖了AndroidX AppCompat库(如果用AndroidX的话):

dependencies {
    implementation 'androidx.appcompat:appcompat:1.6.1'
}

3. 清理编译缓存并重建项目

这种带$的临时文件错误,很多时候是编译缓存导致的异常。执行以下操作:

  • Android Studio中点击Build -> Clean Project
  • 接着点击Build -> Rebuild Project
  • 或者用命令行执行:./gradlew clean assembleDebug(Windows用gradlew.bat clean assembleDebug)

4. 检查Fragment中引用Drawable的方式

在Fragment中引用Drawable时,确保用正确的上下文获取资源:

  • 不要用getContext()直接获取资源,建议用requireContext()或者AppCompatResources.getDrawable(requireContext(), R.drawable.your_selector),后者能更好地兼容VectorDrawable。

比如:

val drawable = AppCompatResources.getDrawable(requireContext(), R.drawable.ic_lose_weight_selector)
yourImageView.setImageDrawable(drawable)

内容的提问来源于stack exchange,提问作者trurohit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:44:20