How to implement endless list with RecyclerView?

前端 未结 30 2707
无人及你
无人及你 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:01

    Check this every thing is explained in detail: Pagination using RecyclerView From A to Z

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView,
                                         int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }
    
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int visibleItemCount = mLayoutManager.getChildCount();
            int totalItemCount = mLayoutManager.getItemCount();
            int firstVisibleItemPosition = mLayoutManager.findFirstVisibleItemPosition();
    
            if (!mIsLoading && !mIsLastPage) {
                if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0) {
                    loadMoreItems();
                }
            }
        }
    })
    

    loadMoreItems():

    private void loadMoreItems() {
        mAdapter.removeLoading();
        //load data here from the server
    
        // in case of success
        mAdapter.addData(data);
        // if there might be more data
        mAdapter.addLoading();
    }
    

    in MyAdapter :

    private boolean mIsLoadingFooterAdded = false;
    
    public void addLoading() {
        if (!mIsLoadingFooterAdded) {
            mIsLoadingFooterAdded = true;
            mLineItemList.add(new LineItem());
            notifyItemInserted(mLineItemList.size() - 1);
        }
    }
    
    public void removeLoading() {
        if (mIsLoadingFooterAdded) {
            mIsLoadingFooterAdded = false;
            int position = mLineItemList.size() - 1;
            LineItem item = mLineItemList.get(position);
    
            if (item != null) {
                mLineItemList.remove(position);
                notifyItemRemoved(position);
            }
        }
    }
    
    public void addData(List data) {
    
        for (int i = 0; i < data.size(); i++) {
            YourDataClass yourDataObject = data.get(i);
            mLineItemList.add(new LineItem(yourDataObject));
            notifyItemInserted(mLineItemList.size() - 1);
        }
    }
    

提交回复
热议问题