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

Android库Vector Drawable资源无法覆盖,求最新解决方案

问题描述

将Android库关联到项目后,想覆盖库内的某个Vector Drawable资源,遇到以下问题:

  • 项目res/drawable目录下添加了同名Vector Drawable,但完全无法覆盖库中的对应资源
  • 字符串、布局等其他类型的资源都能正常覆盖,唯独Drawable不行
  • 用「Go To -> Declaration or Usages」查看资源引用,发现库中的资源被Gradle处理成了这些:
    ic_drawable.xml (..myproject\app\src\main\res\drawable)
    ic_drawable.xml (..user\.gradle\caches\transforms3\..\transformed\mylibrary\res\drawable-anydpi-v24)
    + a list of `ic_drawable.png` of different sizes
    

推测是Gradle自动把库中的Vector Drawable转换成了不同分辨率的PNG,而且这些PNG的资源优先级比项目里的Vector Drawable更高。

可行解决方案

方案1:把项目的Vector Drawable放到高优先级目录

库中的Vector Drawable被生成到了drawable-anydpi-v24目录,这个目录的资源优先级比普通drawable目录高。直接把项目里的同名Vector Drawable移到app/src/main/res/drawable-anydpi-v24文件夹下,就能直接覆盖库的资源。

方案2:禁用库的Vector转PNG功能

在Module级别的build.gradle里加配置,强制不让Gradle把库的Vector Drawable转成PNG:

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }

    buildFeatures {
        vectorDrawables {
            useSupportLibrary = true
        }
    }

    dependencies {
        implementation('com.example:mylibrary:x.x.x') {
            // 禁止生成不同分辨率的PNG
            android {
                defaultConfig {
                    vectorDrawables.generatedDensities = []
                }
            }
        }
    }
}

加了vectorDrawables.generatedDensities = []后,Gradle就不会再为库的Vector Drawable生成PNG,此时库的资源会以原始Vector Drawable存在,项目drawable目录下的同名资源就能正常覆盖。

方案3:直接指定引用项目资源

如果前两个方案不好用,也可以直接绕开覆盖逻辑:

  • 布局里直接写@drawable/ic_drawable,清理项目缓存后,会优先加载项目里的资源
  • 或者给项目资源起个别名,在res/values/attrs.xml里加:
    <resources>
        <drawable name="my_custom_ic">@drawable/ic_drawable</drawable>
    </resources>
    
    之后代码和布局里都用@drawable/my_custom_ic来引用项目的资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 21:40:29