Android实战-RecyclerView+Glide刷新列表的若干bug

news2024/9/21 11:41:54

文章目录

  • 前言
  • 一. RecyclerView中使用Glide出现加载图片闪烁
    • 1.1 提出问题
    • 1.2 查看源码
    • 1.3 ViewTarget和SimpleTarget
  • 二. CustomTarget和CustomViewTarget
    • 2.1 onResourceCleared和onLoadCleared
    • 2.2 onLoadStarted和onResourceLoading
  • 结束

前言

最近在项目中使用RecyclerView+Glide发现了一些bug,在此记录一下。

一. RecyclerView中使用Glide出现加载图片闪烁

1.1 提出问题

Recycler+Glide图片闪烁问题
如上图所示,在使用RecyclerView+Glide的时候会出现,图片多次叠加的问题。首先看下代码:

// 用了BaseQuickAdapter
@Override
protected void convert(BaseViewHolder holder, Bean bean) {
	// loading加载
	final View loading = holder.getView(R.id.loading);
    loading.setVisibility(View.VISIBLE);
    // 省略业务代码...
	Glide.with(getContext())
          .load(url) // 加载数据的URL
          .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) // 图片使用原始尺寸
          .into(new SimpleTarget<Drawable>() { // SimpleTarget已经过时
               		@Override
                public void onResourceReady(@NonNull Drawable resource, 
                							@Nullable Transition<? super Drawable> transition)
          		{
					 // 图片加载完成就隐藏loading                	
                     loading.setVisibility(View.GONE); 
                     imageView.setImageDrawable(resource);
                 }
     		});
}

由于业务上要求需要显示loading,目前所做的是将loading的View置于ImageView下面,如果图片加载完成,那么就需要将loading给隐藏。
经过分析,之所以会上面图片所示的问题,主要还是由于RecyclerView的复用机制导致的。当我快速滑动到顶部的时候,顶部的那些View是复用被移出列表的itemView,但是这些被复用的itemView可能还在加载之前的数据,同时这些itemView还要加载当前位置上需要加载的数据,这就导致加载的时候会先出现被复用之前需要加载的数据,然后再加载复用之后需要加载的数据。

如果将上面的SimpleTarget改为直接into(imageView),就不会出现该问题!那么为什么会出现这种情况呢?

1.2 查看源码

首先看一下Glide在直接into的时候做了啥?
Glide源码:

  @NonNull
  public ViewTarget<ImageView, TranscodeType> into(@NonNull ImageView view) {
    // 省略代码...

	// 主要看buildImageViewTarget
    return into(
        glideContext.buildImageViewTarget(view, transcodeClass),
        /*targetListener=*/ null,
        requestOptions,
        Executors.mainThreadExecutor());
  }

继续跟进:
buildImageViewTarget方法

  @NonNull
  public <X> ViewTarget<ImageView, X> buildImageViewTarget(
      @NonNull ImageView imageView, @NonNull Class<X> transcodeClass) {
    return imageViewTargetFactory.buildTarget(imageView, transcodeClass);
  }

跟进到buildTarget里面
ImageViewTargetFactory

  @NonNull
  @SuppressWarnings("unchecked")
  public <Z> ViewTarget<ImageView, Z> buildTarget(
      @NonNull ImageView view, @NonNull Class<Z> clazz) {
    if (Bitmap.class.equals(clazz)) {
      return (ViewTarget<ImageView, Z>) new BitmapImageViewTarget(view);
    } else if (Drawable.class.isAssignableFrom(clazz)) {
      return (ViewTarget<ImageView, Z>) new DrawableImageViewTarget(view);
    } else {
      throw new IllegalArgumentException(
          "Unhandled class: " + clazz + ", try .as*(Class).transcode(ResourceTranscoder)");
    }
  }

到这里就一目了然了,直接into(imageView),里面使用的是ViewTarget回调加载的图片!
那么ViewTargetSimpleTarget有啥区别导致的这个情况呢?

1.3 ViewTarget和SimpleTarget

首先看看SimpleTarget

@Deprecated
public abstract class SimpleTarget<Z> extends BaseTarget<Z> {
  private final int width;
  private final int height;

  /**
   * Constructor for the target that uses {@link Target#SIZE_ORIGINAL} as the target width and
   * height.
   */
  // Public API.
  @SuppressWarnings("WeakerAccess")
  public SimpleTarget() {
    this(SIZE_ORIGINAL, SIZE_ORIGINAL);
  }

  /**
   * Constructor for the target that takes the desired dimensions of the decoded and/or transformed
   * resource.
   *
   * @param width The width in pixels of the desired resource.
   * @param height The height in pixels of the desired resource.
   */
  // Public API.
  @SuppressWarnings("WeakerAccess")
  public SimpleTarget(int width, int height) {
    this.width = width;
    this.height = height;
  }

  /**
   * Immediately calls the given callback with the sizes given in the constructor.
   *
   * @param cb {@inheritDoc}
   */
  @Override
  public final void getSize(@NonNull SizeReadyCallback cb) {
    if (!Util.isValidDimensions(width, height)) {
      throw new IllegalArgumentException(
          "Width and height must both be > 0 or Target#SIZE_ORIGINAL, but given"
              + " width: "
              + width
              + " and height: "
              + height
              + ", either provide dimensions in the constructor"
              + " or call override()");
    }
    cb.onSizeReady(width, height);
  }

  @Override
  public void removeCallback(@NonNull SizeReadyCallback cb) {
    // Do nothing, we never retain a reference to the callback.
  }
}

SimpleTarget的代码相当简单,继承自BaseTarget抽象类

BaseTarget

@Deprecated
public abstract class BaseTarget<Z> implements Target<Z> {

  private Request request;

  @Override
  public void setRequest(@Nullable Request request) {
    this.request = request;
  }

  @Override
  @Nullable
  public Request getRequest() {
    return request;
  }

  // 很重要后面会讲到
  @Override
  public void onLoadCleared(@Nullable Drawable placeholder) {
    // Do nothing.
  }

  @Override
  public void onLoadStarted(@Nullable Drawable placeholder) {
    // Do nothing.
  }

  @Override
  public void onLoadFailed(@Nullable Drawable errorDrawable) {
    // Do nothing.
  }

  @Override
  public void onStart() {
    // Do nothing.
  }

  @Override
  public void onStop() {
    // Do nothing.
  }

  @Override
  public void onDestroy() {
    // Do nothing.
  }
}

BaseTargetTarget接口的实现。
下面我们来看看ViewTarget的源码:

@Deprecated
public abstract class ViewTarget<T extends View, Z> extends BaseTarget<Z> {
  private static final String TAG = "ViewTarget";
  private static boolean isTagUsedAtLeastOnce;
  private static int tagId = R.id.glide_custom_view_target_tag;

  protected final T view;
  private final SizeDeterminer sizeDeterminer;
  @Nullable private OnAttachStateChangeListener attachStateListener;
  private boolean isClearedByUs;
  private boolean isAttachStateListenerAdded;

  public ViewTarget(@NonNull T view) {
    this.view = Preconditions.checkNotNull(view);
    sizeDeterminer = new SizeDeterminer(view);
  }
  
  @SuppressWarnings("WeakerAccess") // Public API
  @Deprecated
  public ViewTarget(@NonNull T view, boolean waitForLayout) {
    this(view);
    if (waitForLayout) {
      waitForLayout();
    }
  }
	
  // 省略代码...

  private void setTag(@Nullable Object tag) {
    isTagUsedAtLeastOnce = true;
    view.setTag(tagId, tag);
  }

  @Nullable
  private Object getTag() {
    return view.getTag(tagId);
  }

  /**
   * Stores the request using {@link View#setTag(Object)}.
   *
   * @param request {@inheritDoc}
   */
  @Override
  public void setRequest(@Nullable Request request) {
    setTag(request);
  }

  /**
   * Returns any stored request using {@link android.view.View#getTag()}.
   *
   * <p>For Glide to function correctly, Glide must be the only thing that calls {@link
   * View#setTag(Object)}. If the tag is cleared or put to another object type, Glide will not be
   * able to retrieve and cancel previous loads which will not only prevent Glide from reusing
   * resource, but will also result in incorrect images being loaded and lots of flashing of images
   * in lists. As a result, this will throw an {@link java.lang.IllegalArgumentException} if {@link
   * android.view.View#getTag()}} returns a non null object that is not an {@link
   * com.bumptech.glide.request.Request}.
   */
  @Override
  @Nullable
  public Request getRequest() {
    Object tag = getTag();
    Request request = null;
    if (tag != null) {
      if (tag instanceof Request) {
        request = (Request) tag;
      } else {
        throw new IllegalArgumentException(
            "You must not call setTag() on a view Glide is targeting");
      }
    }
    return request;
  }
  // 省略代码...
}

这里最重要的是getRequestsetRequest,它们内部分别调用了getTagsetTag,内部又分别调用了ViewsetTaggetTag方法,通过setTaggetTagRequest对象和View绑定起来。
我们再来看看getRequestsetRequest方法是在哪里调用的。

RequestBuilder

private <Y extends Target<TranscodeType>> Y into(@NonNull Y target,@Nullable RequestListener<TranscodeType> targetListener,BaseRequestOptions<?> options,Executor callbackExecutor) {
    Preconditions.checkNotNull(target);
    if (!isModelSet) {
      throw new IllegalArgumentException("You must call #load() before calling #into()");
    }

    Request request = buildRequest(target, targetListener, options, callbackExecutor);
	
	// 调用ViewTarget的getRequest,也就是获取View里面的Request
    Request previous = target.getRequest();
    
    // 将新的Request和View中的Request对比,如果不一样,就取消View里面的Request
    if (request.isEquivalentTo(previous)
        && !isSkipMemoryCacheWithCompletePreviousRequest(options, previous)) {
      // If the request is completed, beginning again will ensure the result is re-delivered,
      // triggering RequestListeners and Targets. If the request is failed, beginning again will
      // restart the request, giving it another chance to complete. If the request is already
      // running, we can let it continue running without interruption.
      if (!Preconditions.checkNotNull(previous).isRunning()) {
        // Use the previous request rather than the new one to allow for optimizations like skipping
        // setting placeholders, tracking and un-tracking Targets, and obtaining View dimensions
        // that are done in the individual Request.
        previous.begin();
      }
      return target;
    }
	// 清除旧的Request
    requestManager.clear(target);
    
    // 设置新的Request
    target.setRequest(request);
    
    requestManager.track(target, request);

    return target;
  }

上面的代码的意思就是,将新的Request和View中的Request对比,如果不一样,就取消View里面的Request,去加载新的Request。这样做就可以解决前面的问题,被复用的旧的Request会被取消,而去加载新的Request。
至此,搞清楚了为啥直接into(imageView)不会出现图片多次叠加的问题。
修改的代码如下:

Glide.with(getContext())
     .load(url)
     .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) // 图片使用原始尺寸
     .listener(new RequestListener<Drawable>() {
               @Override
               public boolean onLoadFailed(@Nullable GlideException e,Object model, Target<Drawable> target, boolean isFirstResource){
                    loading.setVisibility(View.GONE);
                    return false;
               }

               @Override
               public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                         loading.setVisibility(View.GONE);
                         return false;
                    }
                })
                .into(imageView);

需要注意的是由于使用了ViewTarget,会自动改变Bitmap的大小,我们的业务逻辑是不改变Bitmap大小,所以需要加上override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)使用图片原始尺寸。
修改后:
Recycler+Glide图片闪烁问题解决

二. CustomTarget和CustomViewTarget

2.1 onResourceCleared和onLoadCleared

在解决问题的过程中,会发现Glide4.0后SimpleTargetViewTarget都被废弃掉了,被CustomTarget和CustomViewTarget替代掉了。其实它们内部的主要逻辑和SimpleTargetViewTarget基本上都差不多的。只不过这两个回调需要强制实现onLoadClearedonResourceReadyonResourceReadyonLoadCleared里面被调用。
当Glide的内存缓存池满掉后,就会释放多余的bitmap,而被释放的bitmap,会被主动recycle,可能会使用已经被recycle的图片,导致如下的bug:

Canvas: trying to use a recycled bitmap android.graphics.Bitmap@XXXX

所以Glide4.0后要求我们强制实现这个方法,当然只实现该方法是不行的,还需要给imageView设置为null。

// CustomViewTarget的onResourceCleared
@Override
protected void onResourceCleared(@Nullable Drawable placeholder) {
       // 必须在onResourceCleared中给ImageView设置默认图片或者null.
       imageView.setImageDrawable(null);
}

2.2 onLoadStarted和onResourceLoading

当我尝试用CustomViewTarget解决加载图片闪烁的问题的时候,发现显示加载的View,有的时候会不显示。
出问题的代码如下:

@Override
protected void convert(BaseViewHolder holder, Bean bean) {
		// loading加载
		final View loading = holder.getView(R.id.loading);
    	loading.setVisibility(View.VISIBLE);
		// 省略代码...
   Glide.with(getContext())
     	.load(url)
		.into(new CustomViewTarget<View, Drawable>(imageView) {

                        @Override
                        public void onLoadFailed(@Nullable Drawable errorDrawable) {
                            loading.setVisibility(View.GONE);
                        }

                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            loading.setVisibility(View.GONE);
                            imageView.setImageDrawable(resource);
                        }

                        @Override
                        protected void onResourceCleared(@Nullable Drawable placeholder) {
                            // 必须在onResourceCleared中给ImageView设置默认图片或者null.
                            imageView.setImageDrawable(null);
                            loading.setVisibility(View.GONE);
                        }
                    });
}

通过查看CustomViewTarget的API发现了onResourceLoading,我尝试将loading.setVisibility(View.VISIBLE);放到onResourceLoading里面,解决掉了该问题。
代码上可以看到onResourceLoadingonLoadStarted调用了

  // 通知图片开始加载
  @Override
  public final void onLoadStarted(@Nullable Drawable placeholder) {
    maybeAddAttachStateListener();
    onResourceLoading(placeholder);
  }

最后的解决代码:

@Override
protected void convert(BaseViewHolder holder, Bean bean) {
		// loading加载
		final View loading = holder.getView(R.id.loading);
		// 省略代码...
   Glide.with(getContext())
     	.load(url)
		.into(new CustomViewTarget<View, Drawable>(imageView) {

						@Override
                        protected void onResourceLoading(@Nullable Drawable placeholder) {
                            super.onResourceLoading(placeholder);
                            // loading需要放在该回调中,要不然会出现loading数据错乱的问题
                            loading.setVisibility(View.VISIBLE);
                        }
    
                        @Override
                        public void onLoadFailed(@Nullable Drawable errorDrawable) {
                            loading.setVisibility(View.GONE);
                        }

                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            loading.setVisibility(View.GONE);
                            imageView.setImageDrawable(resource);
                        }

                        @Override
                        protected void onResourceCleared(@Nullable Drawable placeholder) {
                            // 必须在onResourceCleared中给ImageView设置默认图片或者null.
                            imageView.setImageDrawable(null);
                            loading.setVisibility(View.GONE);
                        }
                    });
}

结束

以上就是在使用Recycler+Glide的时候出现的一些bug,以及对这些bug的分析和解决思路。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/440615.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Java——合并两个排序的链表

题目链接 牛客在线oj题——合并两个排序的链表 题目描述 输入两个递增的链表&#xff0c;单个链表的长度为n&#xff0c;合并这两个链表并使新链表中的节点仍然是递增排序的。 数据范围&#xff1a; 0≤n≤1000&#xff0c;−1000≤节点值≤1000 要求&#xff1a;空间复杂…

物联网定位技术|实验报告|实验二 多边定位算法、DV-HOP算法

在WSN定位中常常采用三边定位算法&#xff0c;试画图推导三边定位的计算公式&#xff0c;并表示为矩阵形式。 目录 1. 实验目标 2. 实验要求 3. 算法介绍 3.1基本内容介绍 3.2迭代多边定位算法 3.3 DV-HOP算法 4. 算法实现 4.1迭代多边定位算法 第一步&#xff1a;将数据读入内…

STM32HAL库USART外设配置流程及库函数讲解

HAL库中USART外设配置流程及库函数讲解 一说到串口通信&#xff0c;及必须说一下aRS-232/485协议。232协议标准物理接口就是我们常用的DB9串口线 RS-232电平&#xff1a; 逻辑1&#xff1a;-15~-3 逻辑0&#xff1a; 3~15 COMS电平&#xff1a; 逻辑1&#xff1a;3.3 逻辑0&a…

文件操作【下篇】

文章目录 &#x1f5c3;️5.文件的随机读写&#x1f4c1;5.1. fseek&#x1f4c1;5.2. ftell&#x1f4c1;5.3. rewind &#x1f5c3;️6.文本文件和二进制文件&#x1f5c3;️7.文件读取结束的判定&#x1f4c1;7.1. 被错误使用的 feof &#x1f5c3;️8.文件缓冲区 &#x1f…

如何使用YOLOv8推荐的Roboflow来制作训练自己的数据集

YOLOv8是Ultralytics开发的YOLO目标检测和图像分割模型的最新版本&#xff0c;相较于之前的版本&#xff0c;YOLOv8可以更快速有效地识别和定位图像中的物体&#xff0c;以及更准确地分类它们。 YOLOv8需要大量的训练数据来实现最佳性能。为了让YOLOv8能够有效地识别自己的应用…

【UE】保存游戏的demo

效果 注意左上角的打印信息&#xff0c;每当我按下k键&#xff0c;值就加1。当我关闭后重进游戏&#xff0c;按下k键&#xff0c;值是从上次退出游戏的值开始累加的。 步骤 1.新建蓝图&#xff0c;父类为“SaveGame” 命名为“MySaveGame”并打开 新建一个整型变量&#xff0c…

ODOO业财一体贸易行业ERP全面管理系统(核心流程简介)

前言&#xff1a; 贸易行业的两大管理难点在&#xff1a; 1.订单的跟踪效率&#xff1a;订单从报价、寄样、采购材料、委外加工、质检、入库、出库、收款&#xff0c;跟踪环节多&#xff0c;信息分散&#xff0c;跟单员难以把握订单执行进度&#xff0c;因此也导致延期交货等…

户外电源强制国标发布或加速行业洗牌 未来产品将往大容量及轻量化发展

一、户外电源行业概述 户外电源是一种内置锂离子电池的低碳绿色小型储能设备&#xff0c;又称“大号充电宝”、“便携式储能”。是电化学储能的分支&#xff0c;优在“便捷”&#xff0c;具有多次循环充放电、适配广泛、安全便捷的特点&#xff0c;在户外各场景中应用广泛受到…

Ubuntu安装k8s的Dashboard

介绍 Dashboard 是基于网页的 Kubernetes 用户界面。您可以使用 Dashboard 将容器应用部署到Kubernetes 集群中&#xff0c;也可以对容器应用排错&#xff0c;还能管理集群本身及其附属资源。您可以使用Dashboard 获取运行在集群中的应用的概览信息&#xff0c;也可以创建或者…

从Allegro进行反标

从Allegro进行反标 目的反标流程常见问题 目的 通过反标&#xff0c;可以将Allegro中交换的管脚或重新编排的位号&#xff0c;一键更新到原理图中。 反标流程 从Capture输出最新网表文件&#xff1a; Capture Menu -> Tools -> Creat Netlist将最终的PCB设计文件放在…

Java:MybatisPlus--条件构造器

1、条件构造器类别 ①wrapper&#xff1a;抽象类&#xff0c;条件类的顶层&#xff0c;提供了一些获取和判断相关的方法。 ②AbstractWrapper&#xff1a;抽象类&#xff0c;Wrapper的子类&#xff0c;提供了所有的条件相关方法。 ③AbstractLambdaWrapper&#xff1a;抽象类…

对矩阵规模序列<5,10,3,12,5,50,6>,求矩阵链最优括号化方案

对矩阵规模序列<5,10,3,12,5,50,6>,求矩阵链最优括号化方案 理解符号的含义 n6 矩阵A1A2A3A4A5A6 本质是找一个最优的子结构 1.重要的递推公式 2.关键是求最小的m[i,j]就是乘积次数最少的。 k 的位置只有 j − i 种可能 3.下面是详细的解题的方案 根据矩阵链乘法问题&am…

网络工程师经常搞混的路由策略和策略路由,两者到底有啥区别?

当涉及到网络路由时&#xff0c;两个术语经常被混淆&#xff1a;策略路由和路由策略。虽然这些术语听起来很相似&#xff0c;但它们实际上有着不同的含义和用途。在本文中&#xff0c;我们将详细介绍这两个术语的区别和应用。 一、路由策略 路由策略是指一组规则&#xff0c;用…

算法套路九——二叉树广度优先遍历(层序遍历)

算法套路九——二叉树广度优先遍历&#xff08;层序遍历&#xff09; 算法示例LeetCode102. 二叉树的层序遍历 给你二叉树的根节点 root &#xff0c;返回其节点值的 层序遍历 。 &#xff08;即逐层地&#xff0c;从左到右访问所有节点&#xff09;。 法一&#xff1a;双数组…

二极管初识

二极管初识 二极管的主要参数如下&#xff1a; 一般的二极管可以在正向或反向偏置条件下工作。 当二极管正向偏置时&#xff0c;需要经过一定的电压降&#xff08;硅为0.7V&#xff0c;锗为0.3V&#xff09;&#xff0c;才能让电流开始流动。此后&#xff0c;二极管上的电压…

【Vue】学习笔记-绑定样式/条件样式

绑定样式/条件样式 绑定样式条件渲染 绑定样式 class样式 写法 :class"xxx" xxx可以是字符串&#xff0c;对象&#xff0c;数组 字符串写法适用于&#xff1a;类名不确定&#xff0c;要动态获取。 对象写法适用于&#xff1a;要绑定多个样式&#xff0c;个数不确定&…

如何给ClickHouse表生成随机真实测试数据

学习ClickHouse数据库&#xff0c;通常需要下载官网一些示例数据。我们也可以通过内置函数generateRandom快速生成测试数据&#xff0c;从而测试学习一些特性的性能及底层原理。 函数语法 generateRandom函数基于给定schema生成随机数据&#xff0c;用于填充测试表。不是所有类…

【SSM】SpringMVC(三:SpringMVC拦截器)

文章目录 1. 登录案例2. 拦截器2.1 应用2.2 拦截器的执行原理2.3 拦截器执行的时机2.4 拦截器的实现方法2.5 拦截器的实现步骤2.6 开发拦截器 1. 登录案例 【login.jsp】 <%--Created by IntelliJ IDEA.User: BeyongDate: 2023/4/17Time: 11:43To change this template use…

【虹科】深度相机对比测评:虹科HK OAK-D Pro VS 英特尔RealSense D435i

虹科致力于为用户提供最优的机器视觉解决方案。本文将用虹科的AI深度相机与英特尔的深度相机来做图像的对比测试&#xff0c;那么它们有哪些性能差异呢&#xff1f; 虹科深度相机 HK OAK-D Pro有两个核心功能&#xff1a;红外激光点阵投影仪和红外照明LED。 红外激光点阵投影…

不能使用chatGPT?这3个平替甚至比chatGPT更强

不能使用chatGPT&#xff1f;这3个平替甚至比chatGPT更强 chatGPT&#xff0c;一款由OpenAI开发的新型AI聊天机器人&#xff0c;正在势如破竹地改变着许多人的工作和生活方式。作为一款基于大语言模型的聊天机器人&#xff0c;chatGPT能够理解自然语言并进行人机对话。与传统的…