RecyclerView连续调用LoadMore分页

时间:2018-09-17 16:45:02

标签: android android-recyclerview pagination

我正在尝试使用下面的代码实现分页,并且它可以很好地与片段一起使用,但是当我在嵌套片段中实现它时,它将加载所有数据(连续加载第一页和所有下一页)。问题是我的总项目数为12,时间可见的时间为3,但是layoutManager.getChildCount()给我的总项目数为12(layoutManager.getItemCount()),因此它开始连续加载下一页。

这是oNScroll代码:

  public PaginationScrollListener(LinearLayoutManager layoutManager) {
    this.layoutManager = layoutManager;
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);

    int visibleItemCount = layoutManager.getChildCount();
    int totalItemCount = layoutManager.getItemCount();
    int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

    if (!isLoading() && !isLastPage()) {
        if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                && firstVisibleItemPosition >= 0
                && totalItemCount >= getTotalPageCount()) {
            loadMoreItems();
        }
    }

}

滚动并请求下一页时:

        recyclerView.addOnScrollListener(new PaginationScrollListener(layoutManager) {
        @Override
        protected void loadMoreItems() {
            isLoading = true;
            currentPage += 1;

            // mocking network delay for API call
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadNextPage();
                }
            }, 1000);
        }

        @Override
        public int getTotalPageCount() {
            return TOTAL_PAGES;
        }

        @Override
        public boolean isLastPage() {
            return isLastPage;
        }

        @Override
        public boolean isLoading() {
            return isLoading;
        }
    });

1 个答案:

答案 0 :(得分:0)

按如下所示更改滚动侦听器:

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if(dy>0){  //if is scrolling vertically
   int visibleItemCount = layoutManager.getChildCount();
   int totalItemCount = layoutManager.getItemCount();
   int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
   if (!isLoading() && !isLastPage()) {
      if (firstVisibleItemPosition + visibleItemCount >= totalItemCount) {
      //make your request here
   }
}
}});