How to load more data in recycler view from server?

前端 未结 3 1637
一个人的身影
一个人的身影 2021-01-17 06:30

I have a recycler view in which I load some data from the server when user scroll to bottom I want to show a progress bar and send another request to the server for more dat

3条回答
  •  独厮守ぢ
    2021-01-17 06:50

    Use Below Code:

    First Declare these global variables:

    int visibleItemCount, totalItemCount = 1;
    int firstVisiblesItems = 0;
    int totalPages = 1; // get your total pages from web service first response
    int current_page = 0;
    
    boolean canLoadMoreData = true; // make this variable false while your web service call is going on.
    
    LinearLayoutManager linearLayoutManager;
    

    Assign Layout manager to your Recyclerview:

    linearLayoutManager = new LinearLayoutManager(mActivity);
    mRecyclerView.setLayoutManager(linearLayoutManager);
    

    Scroll Listener of your recyclerview:

    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (dy > 0) //check for scroll down
                {
                    visibleItemCount = linearLayoutManager.getChildCount();
                    totalItemCount = linearLayoutManager.getItemCount();
                    firstVisiblesItems = linearLayoutManager.findFirstVisibleItemPosition();
    
                        if (canLoadMoreData) {
                            if ((visibleItemCount + firstVisiblesItems) >= totalItemCount) {
                                if (current_page < totalPages) {
                                    canLoadMoreData  = false;
                                    /**
                                     * .
                                     * .
                                     * .
                                     * .call your webservice with page index
                                     * .
                                     * .
                                     *
                                     */
                                    //After completion of web service make 'canLoadMoreData = true'
                                }
                            }
                        }
    
                }
            }
        });
    

提交回复
热议问题