通过Gilde+RecycleView实现滑动时不加载、停止滑动

2017-08-27  本文已影响0人  AndyWei123
image.png ![AutoRecycleView.gif](https://img.haomeiwen.com/i6762069/ce4de6d23702aa4b.gif?imageMogr2/auto-orient/strip)

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

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

下面是RecycleView的效果和源码

AutoRecycleView.gif
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;
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读