How to implement endless list with RecyclerView?

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

    Most answer are assuming the RecyclerView uses a LinearLayoutManager, or GridLayoutManager, or even StaggeredGridLayoutManager, or assuming that the scrolling is vertical or horyzontal, but no one has posted a completly generic answer.

    Using the ViewHolder's adapter is clearly not a good solution. An adapter might have more than 1 RecyclerView using it. It "adapts" their contents. It should be the RecyclerView (which is the one class which is responsible of what is currently displayed to the user, and not the adapter which is responsible only to provide content to the RecyclerView) which must notify your system that more items are needed (to load).

    Here is my solution, using nothing else than the abstracted classes of the RecyclerView (RecycerView.LayoutManager and RecycerView.Adapter):

    /**
     * Listener to callback when the last item of the adpater is visible to the user.
     * It should then be the time to load more items.
     **/
    public abstract class LastItemListener extends RecyclerView.OnScrollListener {
    
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
          super.onScrolled(recyclerView, dx, dy);
    
          // init
          RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
          RecyclerView.Adapter adapter = recyclerView.getAdapter();
    
          if (layoutManager.getChildCount() > 0) {
            // Calculations..
            int indexOfLastItemViewVisible = layoutManager.getChildCount() -1;
            View lastItemViewVisible = layoutManager.getChildAt(indexOfLastItemViewVisible);
            int adapterPosition = layoutManager.getPosition(lastItemViewVisible);
            boolean isLastItemVisible = (adapterPosition == adapter.getItemCount() -1);
    
            // check
            if (isLastItemVisible)
              onLastItemVisible(); // callback
         }
       }
    
       /**
        * Here you should load more items because user is seeing the last item of the list.
        * Advice: you should add a bollean value to the class
        * so that the method {@link #onLastItemVisible()} will be triggered only once
        * and not every time the user touch the screen ;)
        **/
       public abstract void onLastItemVisible();
    
    }
    
    
    // --- Exemple of use ---
    
    myRecyclerView.setOnScrollListener(new LastItemListener() {
        public void onLastItemVisible() {
             // start to load more items here.
        }
    }
    

提交回复
热议问题