How to implement endless list with RecyclerView?

前端 未结 30 2705
无人及你
无人及你 2020-11-22 02:22

I would like to change ListView to RecyclerView. I want to use the onScroll of the OnScrollListener in RecyclerView to determine if a

30条回答
  •  一生所求
    2020-11-22 03:19

    This solution works perfectly for me.

    //Listener    
    
    public abstract class InfiniteScrollListener     extendsRecyclerView.OnScrollListener {
    
    public static String TAG = InfiniteScrollListener.class.getSimpleName();
    int firstVisibleItem, visibleItemCount, totalItemCount;
    private int previousTotal = 0;
    private boolean loading = true;
    private int visibleThreshold = 1;
    private int current_page = 1;
    
    private LinearLayoutManager mLinearLayoutManager;
    
    public InfiniteScrollListener(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 <= visibleThreshold)) {
    
            current_page++;
    
            onLoadMore(current_page);
    
            loading = true;
        }
    }
    
    public void resetState() {
        loading = true;
        previousTotal = 0;
        current_page = 1;
    }
    
    public abstract void onLoadMore(int current_page);
    }
    
    //Implementation into fragment 
     private InfiniteScrollListener scrollListener;
    
    scrollListener = new InfiniteScrollListener(manager) {
            @Override
            public void onLoadMore(int current_page) {
                //Load data
            }
        };
        rv.setLayoutManager(manager);
        rv.addOnScrollListener(scrollListener);
    

提交回复
热议问题