使用Glide 4.6.1重复加载矢量Drawable资源异常问题咨询
Hey there, that's a super weird bug—loading the same vector Drawable but occasionally getting a random image like Emily Blunt? Let's break down what's happening and fix it.
Why This Happens
The root issue here is how you're passing the Drawable to Glide. When you use AppCompatResources.getDrawable(context, resId) to fetch a Drawable instance and feed that to Glide's .load() method, Glide struggles to generate a consistent cache key for it. Over time, this leads to cache collisions, where Glide pulls the wrong cached image instead of your intended vector resource.
The Fixes
Let's go through the most reliable solutions:
1. Load the Resource ID Directly (Best Permanent Fix)
Glide is built to handle resource IDs natively, especially for vector Drawables. Instead of passing a pre-fetched Drawable instance, pass the resId directly. This lets Glide manage the Drawable loading and caching correctly, eliminating the cache collision problem entirely.
Here's your updated code:
fun AppCompatImageView.loadCircleImage(resId: Int, width: Int, height: Int) { val options = RequestOptions() .fitCenter() .override(width, height) .circleCrop() Glide.with(context) .load(resId) // Use the resource ID directly instead of a Drawable instance .apply(options) .into(this) }
2. Clear Glide's Cache (Temporary Quick Fix)
If you need an immediate workaround before updating the code, you can clear Glide's cache to get rid of the incorrect cached image. Run these lines once (for example, in your app's onCreate):
Glide.get(context).clearMemory() Glide.get(context).clearDiskCache()
Note: This will wipe all cached images, so it's not a long-term solution—stick with the first fix for lasting results.
3. Upgrade Glide to a Newer Version
Glide 4.6.1 is quite outdated (released back in 2018) and has known bugs with vector Drawable handling and caching logic. Upgrading to a newer stable version (like 4.12.0 or later) will fix many of these issues out of the box. Just update your dependency in build.gradle:
implementation 'com.github.bumptech.glide:glide:4.12.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
Why the Random Image?
That random image (like Emily Blunt's) is just a previously cached image that Glide is pulling by mistake, thanks to the broken cache key generated from the Drawable instance. Using the resource ID fixes the cache key generation, so Glide will always fetch the correct vector Drawable.
内容的提问来源于stack exchange,提问作者AndroidRuntimeException

