Pagination in recycler view

Sometimes we want to load a lot of data from API and see that loading all the data at a time is not reasonable, so we use pagination concept to make the loading of data look better.

Pagination is the process of dividing a page into its smaller elements which we can load according to our requirement.

In android application, if you are using recycler view and want to implement simple pagination concept then follow the following steps...

On your recycler view instance call a method addOnScrollListener(), and pass an object of the RecyclerView.OnScrollListener() into it.

After this, you have an overridden method onScrolled(), write your logic for the scrolling recycler view.

Inside the onScrolled(RecyclerView recyclerView, int dX, int dY).

Now, take three int variables in which you will store integer values that you get by calling these methods on layoutManager object
1.getChildCount(),
2.getItemCount(),
3.findFirstVIsibleItemPosition()

Now check if the views created by recycler view is the total views that the recycler view has,
if yes then perform whatever task you want to perform through pagination.

A sample code is here take a look and try on your own to implement pagination with recycler view.

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

            if (loading) {
                if ((visibleItemCount + pastVisibleItems) == totalItemCount) {
                    //TODO pagination &  fetch new data                    
                      progressBarPaginationLoading.setVisibility(View.VISIBLE);                 
            }
        }
    }
});


If you like it keep sharing......

I have built an application with the pagination and providing you git repository URL check out the app if you need more help.

GitHub: https://goo.gl/mYiACj

Facebook: https://www.facebook.com/techfreakravissingh/

Twitter: https://twitter.com/tech_freak_ravi




Comments

Popular Posts