欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

上拉自动加载的recyclerView

程序员文章站 2022-05-05 08:55:27
...

做项目时下拉刷新控件可以直接用google提供,上拉加载更多需要自己实现,在此自己封装了一个recyclerView,根据recyclerView里面的childview数量判断是否继续请求下一页。有一个缺点是上拉加载更多时会多请求一次空数据。

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

/**
 * @author zhangxiaohui
 * create at 2018/12/29
 */
public class AutoLoadRecyclerView extends RecyclerView {
    private final int PAGE_SIZE = 15, AUTO_LOAD_POS = 5;
    private int repeatLoad = 0;
    private int lastItemCount = PAGE_SIZE + 1;

    public AutoLoadRecyclerView(Context context) {
        super(context);
    }

    public AutoLoadRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void setOnListner(final AutoLoadMoreListner autoLoadMoreListner) {
        this.addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState != SCROLL_STATE_IDLE) {//滚动状态不加载
                    return;
                }
                LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    //获取最后一个可见view的位置
                    int lastItemPosition = linearManager.findLastVisibleItemPosition();
                    if (linearManager.getItemCount() == PAGE_SIZE) {//此行重置下拉刷新后可以正常进行分布上拉加载
                        lastItemCount = PAGE_SIZE + 1;
                        repeatLoad = 0;
                    }
                    if (linearManager.getItemCount() < PAGE_SIZE) {//总条数小于一页的数量不再请求下一页
                        return;
                    }
                    //上一次总条数与最新获取的总条数相同不再请求,请求多一次以解决第一页返回PAGE_SIZE数量
                    if ((linearManager.getItemCount() - 1) == lastItemCount && repeatLoad > 1) {
                        return;
                    }
                    repeatLoad++;
                    lastItemCount = lastItemPosition;
                    if (lastItemPosition >= (linearManager.getItemCount() - AUTO_LOAD_POS)) {
                        autoLoadMoreListner.autoLoadMoreData();
                    }
                }
            }
        });
    }

    public interface AutoLoadMoreListner {
        void autoLoadMoreData();
    }
}

 

相关标签: recyclerView