You need to enable JavaScript to run this app. 使用BlurImageView在自定义GridView时报BitmapDrawable.getBitmap()空指针如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

使用BlurImageView在自定义GridView时报BitmapDrawable.getBitmap()空指针如何解决?

问题根因

你遇到的空指针异常是因为调用image.setBlur(15)时,Glide还未完成网络图片的加载,BlurImageView内部持有的Drawable为null,库方法内部调用BitmapDrawable.getBitmap()时就触发了空指针。你用固定2秒延迟的Timer方案不可靠,网络波动、图片体积差异、GridView的Item复用逻辑都可能导致到了预设时间图片仍未加载完成,同时Timer还可能引发内存泄漏、Item内容错乱的问题。

修复方案

  1. 废弃Timer延迟逻辑,改用Glide的加载完成回调,确保图片加载成功后再执行模糊操作,示例代码如下:
// 绑定Item前先清理旧请求,避免Item复用导致内容错乱
Glide.with(getApplicationContext()).clear(image);
image.setVisibility(View.INVISIBLE);
Glide.with(getApplicationContext())
     .load(Uri.parse(lmap.get((int)_position).get("pic").toString()))
     .listener(new RequestListener<Drawable>() {
         @Override
         public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
             // 加载失败的兜底逻辑,可自行设置错误占位图
             image.setVisibility(View.VISIBLE);
             return false;
         }

         @Override
         public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
             image.setVisibility(View.VISIBLE);
             // 增加类型判断,避免非BitmapDrawable场景触发异常
             if (resource instanceof BitmapDrawable) {
                 image.setBlur(15);
             }
             return false;
         }
     })
     .into(image);
  1. 可选优化:可以在布局中给BlurImageView设置默认占位图,就算网络加载失败也能保证内部有默认Bitmap,不会触发空指针。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 07:36:01