RecyclerView实现分批分页、上拉加载更多功能

RecyclerView越来越替代ListView,如何上拉加载更多呢?

Step 1:自定义Listener继承recyclerView的OnScrollListener

public abstract class EndLessOnScrollListener extends RecyclerView.OnScrollListener {

    //声明一个LinearLayoutManager
    private LinearLayoutManager mLinearLayoutManager;

    //当前页,从0开始
    private int currentPage = 0;

    //已经加载出来的Item的数量
    private int totalItemCount;

    //主要用来存储上一个totalItemCount
    private int previousTotal = 0;

    //在屏幕上可见的item数量
    private int visibleItemCount;

    //在屏幕可见的Item中的第一个
    private int firstVisibleItem;

    //是否正在上拉数据
    private boolean loading = true;

    public EndLessOnScrollListener(LinearLayoutManager linearLayoutManager) {
        this.mLinearLayoutManager = linearLayoutManager;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        visibleItemCount = recyclerView.getChildCount();
        totalItemCount = mLinearLayoutManager.getItemCount();
        firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();
        if (loading) {
    
            if (totalItemCount > previousTotal) {
                //说明数据已经加载结束
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        //这里需要好好理解
        if (!loading && totalItemCount - visibleItemCount <= firstVisibleItem) {
            currentPage++;
            onLoadMore(currentPage);
            loading = true;
        }
    }

    /**
     * 提供一个抽闲方法,在Activity中监听到这个EndLessOnScrollListener
     * 并且实现这个方法
     */
    public abstract void onLoadMore(int currentPage);

}

 

Step 2:调用的地方

private Handler handler = new Handler();

 

mRecyclerView.addOnScrollListener(new EndLessOnScrollListener(mLinearLayoutManager) {
    @Override
    public void onLoadMore(int currentPage) {

        if (pageIndex == pages) {
            return;
        }
        showWaitDialog();
        handler.postDelayed(new Runnable() {
            public void run() {
                //请求网络
                pageIndex++;
                getData();
                mAdapter.notifyDataSetChanged();
            }
        }, 500);
    }
});

 

你可能感兴趣的:(香蕉---工具类,橘子---圆又圆)