Glide 4.6.1加载SVG图片失败抛出java.lang.IllegalStateException求助
解决Glide 4.6.1加载SVG图片失败的问题
我之前也踩过Glide从3.x升级到4.x后SVG加载失败的坑,这俩版本的API差异真的不小,尤其是资源加载的注册逻辑完全重构了,你遇到的java.lang.IllegalStateException大概率是因为没跟上4.x的配置规范。下面给你一步步拆解解决方法:
1. 先把依赖配对
首先得确保项目里引入了Glide 4.6.1对应的SVG扩展依赖,版本必须和核心库完全一致,不然很容易出兼容问题。在Module级别的build.gradle里加上这些:
dependencies { // Glide核心库 implementation 'com.github.bumptech.glide:glide:4.6.1' annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1' // SVG扩展库,版本要和核心库严格对应 implementation 'com.github.bumptech.glide:svg:4.6.1' }
2. 自定义Glide模块注册SVG解码器
Glide 4.x不再像3.x那样靠手动设置ModelLoader,而是需要通过AppGlideModule来注册自定义的解码器和转换器,这一步是核心,没做的话Glide根本认不出SVG格式。新建一个类:
import android.content.Context; import com.bumptech.glide.annotation.GlideModule; import com.bumptech.glide.module.AppGlideModule; import com.bumptech.glide.Registry; import com.caverock.androidsvg.SVG; import com.bumptech.glide.samples.svg.SvgDecoder; import com.bumptech.glide.samples.svg.SvgDrawableTranscoder; import com.bumptech.glide.load.resource.drawable.PictureDrawable; @GlideModule public class MyAppGlideModule extends AppGlideModule { @Override public void registerComponents(Context context, com.bumptech.glide.Glide glide, Registry registry) { // 注册SVG的解码器和转码器,让Glide能处理SVG资源 registry.register(SVG.class, PictureDrawable.class, new SvgDrawableTranscoder()) .append(java.io.InputStream.class, SVG.class, new SvgDecoder()); } // 可选:禁用Manifest解析,能稍微提升Glide的初始化速度 @Override public boolean isManifestParsingEnabled() { return false; } }
注意:加了
@GlideModule注解后,一定要重新编译项目,Glide会自动生成一个叫GlideApp的类,后面加载图片要用到它。
3. 用4.x的正确姿势加载SVG
Glide 4.x的加载方式和3.x完全不一样,别再用旧的链式调用了,换成下面的写法:
// 推荐方式:用自动生成的GlideApp GlideApp.with(yourContext) .as(PictureDrawable.class) .transition(com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade()) .diskCacheStrategy(com.bumptech.glide.load.engine.DiskCacheStrategy.RESOURCE) .load("你的SVG图片URL") .into(yourImageView); // 备选:手动构建RequestBuilder(如果GlideApp没生成的话) com.bumptech.glide.request.RequestBuilder<PictureDrawable> svgRequestBuilder = com.bumptech.glide.Glide.with(yourContext) .as(PictureDrawable.class) .transcode(new SvgDrawableTranscoder(), PictureDrawable.class) .source(new SvgDecoder()) .apply(com.bumptech.glide.request.RequestOptions.fitCenterTransform()); svgRequestBuilder.load("你的SVG图片URL") .into(yourImageView);
最后排查下可能的坑
如果还是报异常,先检查这几点:
- 确认
MyAppGlideModule上的@GlideModule注解没写错,并且项目已经重新编译,GlideApp类存在 - 检查SVG扩展库和Glide核心库的版本完全一致,差一点都可能出问题
- 确认AndroidManifest.xml里加了网络权限:
<uses-permission android:name="android.permission.INTERNET"/>,不然连图片都拉不到
内容的提问来源于stack exchange,提问作者Developer
相关产品推荐
相关产品推荐

