How to implement endless list with RecyclerView?

前端 未结 30 2655
无人及你
无人及你 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 02:57

    1. Create an abstract class and extends RecyclerView.OnScrollListener

      public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
      private int previousTotal = 0;
      private boolean loading = true;
      private int visibleThreshold;
      private int firstVisibleItem, visibleItemCount, totalItemCount;
      private RecyclerView.LayoutManager layoutManager;
      
      public EndlessRecyclerOnScrollListener(RecyclerView.LayoutManager layoutManager, int visibleThreshold) {
      this.layoutManager = layoutManager; this.visibleThreshold = visibleThreshold;
      }
      @Override
      public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
      super.onScrolled(recyclerView, dx, dy);
      
      visibleItemCount = recyclerView.getChildCount();
      totalItemCount = layoutManager.getItemCount();
      firstVisibleItem = ((LinearLayoutManager)layoutManager).findFirstVisibleItemPosition();
      
      if (loading) {
          if (totalItemCount > previousTotal) {
              loading = false;
              previousTotal = totalItemCount;
          }
      }
      if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
          onLoadMore();
          loading = true;
      }
        }
      
      public abstract void onLoadMore();}
      
    2. in activity (or fragment) add addOnScrollListener to recyclerView

      LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
      recyclerView.setLayoutManager(mLayoutManager);
      recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager, 3) {
          @Override
          public void onLoadMore() {
              //TODO
              ...
          }
      });
      

提交回复
热议问题