RecyclerView+gllide加载很多大图,快速滑动卡顿解决方案

思路 :实现滑动时不加载、停止滑动后再开始加载图片

在这里插入图片描述

这是RecycleView的工作机制 ,我们可以看到没当显示的时候都会执行BindViewHolder而这正是我们调用Gilde加载图片的位置 所有假如在滑动过程中也加载图片的话无疑很耗费性能,那么我们要怎么做呢,其实只需要重写一下RecycleView的onScrollStateChanged方法在里面约定好Gilde是否可以加载图片。

我们先说一下onScrollStateChanged的几种状态。

SCROLL_STATE_IDLE 屏幕停止滚动

SCROLL_STATE_DRAGGING 屏幕滚动且用户使用的触碰或手指还在屏幕上

SCROLL_STATE_SETTLING 由于用户的操作,屏幕产生惯性滑动

而Gilde同时也为我们提供了两个方法

resumeRequests() 开始加载图片

pauseRequests() 停止加载图片

自定义RecyclerView


public class AutoLoadRecyclerView extends RecyclerView {
    
    
    public AutoLoadRecyclerView(Context context) {
    
    
        this(context, null);
    }

    public AutoLoadRecyclerView(Context context, AttributeSet attrs) {
    
    
        this(context, attrs, 0);
    }

    public AutoLoadRecyclerView(Context context, AttributeSet attrs, int defStyle) {
    
    
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
    
    
        addOnScrollListener(new ImageAutoLoadScrollListener());
    }

    //监听滚动来对图片加载进行判断处理
    public class ImageAutoLoadScrollListener extends OnScrollListener {
    
    
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    
    
            super.onScrolled(recyclerView, dx, dy);
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
    
    
            super.onScrollStateChanged(recyclerView, newState);
            switch (newState) {
    
    
                case SCROLL_STATE_IDLE: // The RecyclerView is not currently scrolling.
                    //当屏幕停止滚动,加载图片
                    try {
    
    
                        if (getContext() != null) Glide.with(getContext()).resumeRequests();
                    } catch (Exception e) {
    
    
                        e.printStackTrace();
                    }
                    break;
                case SCROLL_STATE_DRAGGING: // The RecyclerView is currently being dragged by outside input such as user touch input.
                    //当屏幕滚动且用户使用的触碰或手指还在屏幕上,停止加载图片
                    try {
    
    
                        if (getContext() != null) Glide.with(getContext()).pauseRequests();
                    } catch (Exception e) {
    
    
                        e.printStackTrace();
                    }
                    break;
                case SCROLL_STATE_SETTLING: // The RecyclerView is currently animating to a final position while not under outside control.
                    //由于用户的操作,屏幕产生惯性滑动,停止加载图片
                    try {
    
    
                        if (getContext() != null) Glide.with(getContext()).pauseRequests();
                    } catch (Exception e) {
    
    
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }
}

转载:https://juejin.cn/post/6935743990285205511

猜你喜欢

转载自blog.csdn.net/gqg_guan/article/details/132109340