Friday, 22 July 2016

onScroll event of RecyclerView and Pagination

RecyclerView is the most usable view in android development due to its features and ease of usability that it provides. This post is regarding the one of the features of RecyclerView that is its ScrollEvent. If you are having thousand of records from your server, than in the case instead of requesting all the records at one time only or you can say in a single request only which will put load on your server as well as it is time consuming, you can do it in efficient way. This can be done through the addOnScrollListener in your RecyclerView. This is called Pagination. The addOnScrollListener of RecyclerView allows you to know the the last item of your data list has been reached and now you can request for new set of records. This can be implemented as follows:-

1. add the scrollListener to your recycler view as follows :-

private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;

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();
            pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

            if (loading) 
            {
                if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount) 
                {
                    loading = false;
                    Toast.makeText(getActivity(),"Last item reached",Toast.LENGTH_SHORT).show();
                   //here you can do the pagination code to request for new set of records
                }
            }
        }
    }
});  

2. add the new layoutmanager to your recycler view as follows:-

LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);

That' all.. now you can scroll your recyclerview and add pagination to it.

No comments:

Post a Comment