Home » Android » Automatically load images of next page on recyclerview scrolling

Automatically load images of next page on recyclerview scrolling

Posted by: admin November 1, 2017 Leave a comment

Questions:

I am using pixabay’s api to show images in my recyclerview in grid layout.
Everything is working fine,i want to show images of next page in the same activity when user reaches end of images in recyclerview of first page i.e. when user reaches end of recyclerview make another request and increase page by 1 and show images of next page at the same time i want to keep images of first page as it is,if the user scrolls up again it should see images of first page.Here is my request.

https://pixabay.com/api/?q=yellow&key=MY_API_KEY&image_type=photo&page=1

How to automatically increase page no when user reaches end of recyclerview. I don’t want to show buttons at the end of recyclerview for next page images

Answers:

I think you’ll need to implement addOnSrollListener() in your recyclerview.
You should implement something like that:

listRepositories.addOnScrollListener(new 
    RecyclerView.OnScrollListener() {

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

            int pastVisibleItems, visibleItemsCount, totalItemCount;

            if (dy > 0) {
                visibleItemsCount = layoutManager.getChildCount();
                pastVisibleItems = layoutManager.findFirstVisibleItemPosition();
                totalItemCount = layoutManager.getItemCount();

                if ((visibleItemsCount + pastVisibleItems) >= totalItemCount) {
                    // method where you get your images
                    load(currentPage++);
                }

            }
        }

    });