Glide加载CompoundDrawable时error配置失效,如何处理加载错误?
解决Glide加载CompoundDrawable时Error配置失效的问题
这个问题的核心原因是:当你使用**自定义SimpleTarget**时,Glide的RequestOptions.error()配置不会自动帮你把错误图片设置到TextView的CompoundDrawable上——因为这个Target的逻辑完全由你自己实现,Glide只会在加载成功时调用onResourceReady,而加载失败的情况需要你手动处理。
解决方案:重写SimpleTarget的onLoadFailed方法
你只需要在SimpleTarget中添加onLoadFailed的实现,在这个方法里加载你的错误图片(或者直接使用资源文件里的错误图),然后设置为TextView的CompoundDrawable即可。
修改后的完整代码如下:
RequestOptions options = new RequestOptions() .error(R.drawable.error_image) .fitCenter() .circleCrop(); Glide.with(context) .setDefaultRequestOptions(options) .load(sandwich.getImage()) .into(new SimpleTarget<Drawable>(100,100) { @Override public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) { // 加载成功时设置正常图片 sandwichQuickInfo.setCompoundDrawablesWithIntrinsicBounds( resource, null, null, null ); } @Override public void onLoadFailed(@Nullable Drawable errorDrawable) { super.onLoadFailed(errorDrawable); // 加载失败时设置错误图片,兜底处理防止null if (errorDrawable == null) { errorDrawable = ContextCompat.getDrawable(context, R.drawable.error_image); } sandwichQuickInfo.setCompoundDrawablesWithIntrinsicBounds( errorDrawable, null, null, null ); } });
额外说明
- 为什么原来的
error()没生效?因为RequestOptions.error()主要是给Glide内置的Target(比如ImageViewTarget)设计的,内置Target会自动处理错误回调并设置error资源。但自定义SimpleTarget没有这个默认逻辑,必须手动实现失败处理。 - 你也可以选择使用
RequestListener来监听加载状态,然后在onLoadFailed回调里设置错误图,但直接重写SimpleTarget的onLoadFailed是更直接的方式。
内容的提问来源于stack exchange,提问作者Avid Programmer
相关产品推荐
相关产品推荐

