Android RecyclerView adding pagination

旧巷老猫 提交于 2019-12-06 03:03:23

You can try this approach:

  mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
{
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        if (dy > 0) //check for scroll down
        {
            visibleItemCount = mLayoutManager.getChildCount();
            totalItemCount = mLayoutManager.getItemCount();
            pastVisibleItems = mLayoutManager.findFirstVisibleItemPosition();

            if (loading) {
                if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
                    loading = false;
                    if (adapter.countOfShowing < adapter.allChallenges.size()) {
                        Log.e("...", "Last Item Wow !");
                        adapter.increaseCountOfShowing();
                        adapter.notifyDataSetChanged();
                    }
                    loading = true;
                    //Do pagination.. i.e. fetch new data
                }
            }
        }
    }
});

https://github.com/kunal-mahajan/PaginationAdeptor

I have implemented the pagination component / widget and that is very simple to implement. No xml is required only need to extend the class. Example is available in above url with timer task and dummy data. In main activity you may change the number of data available for testing purpose in "final int totalRecords"; If there is any issue will answer your queries. Thanks Kunal

What we did was use ReyclerView.OnScrollListener. Assuming you're using a LinearLayoutManager, you can check the current shown item versus the total count to determine when you've reached the last item, then request the next page. You also need to throw in some additional logic checks to early out to prevent "spamming" as the scroll even happens a lot.

For example:

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        if (!hasMoreContent()) {
            return;
        }

        if (currentlyLoadingInitialRequest()) {
            return;
        }

        if (alreadyLoadingNextPage()) {
            return;
        }

        if (isInErrorState()) {
            return;
        }

        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        int total = layoutManager.getItemCount();
        int currentLastItem = layoutManger.findLastVisibleItemPosition();
        if (currentLastItem == total - 1) {
            requestNextPage();
        }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!