How to add Load More / Infinite Scrolling in Android using Kotlin
- August 27, 2019
- John Codeos
In this tutorial, I’m going to show you how to add the Load More / Infinite Scrolling feature in the RecyclerView that has a Linear, Grid or Staggered Grid Layout.
But first, let’s set up the files which are important for whatever layout you choose to implement.
Setting up Load More / Infinite Scrolling
First, let’s start by creating the layout that contains the circular progress bar we show when we load more data (progress_loading.xml):
After that, create the ScrollListener for our RecyclerView (RecyclerViewLoadMoreScroll.kt):
In this example, we set the visibleThreshold to 5, which means the circular progress bar will show up when the user sees the 5th item from the end of our downloaded data.
Next, we have to create an interface where we are calling to load more data into our RecyclerView (OnLoadMoreListener):
Also, we need to create a file (if you don’t have one already in your project) with a name Constant.kt and paste the following code:
This file contains the IDs for our Item View and Loading View, so the RecyclerView can call the right view in the right moment.
Now we go to our file RecyclerViewActivity.kt where the RecyclerView lives, and we’re going to create an ArrayList called loadMoreItemsCells.
loadMoreItemsCells contains the items we load when we show the circular progress bar (Loading View).
Also, we call the methods setRVLayoutManager() and we set our RecyclerView Layout and setRVScrollListener(), where we add the ScrollListener we created before:
But we’re not finished yet!
Now in the Recycler’s View Adapter file we’re going to add some methods that add the data we downloaded during Loading (loadMoreItemsCells) to our main ArrayList (itemsCells), and also add methods that know when to show or hide our Loading View:
For a RecyclerView with Linear Layout we have to add the following methods in our RecyclerViewActivity.kt file:
That’s it! Run the project and…
A RecyclerView with Grid Layout is a little bit different than the other layouts, and we have to add the following methods into our RecyclerViewActivity.kt file:
The difference in Grid Layout from the others is that we have to set the grid columns to 1 to be the full width of the recyclerView (lines 6-14), when we want to show the Loading View.
Let’s run the project!
Staggered Grid Layout
The Layout Manager of a RecyclerView with a Staggered Layout is the same as Linear:
But it’s a little bit tricky when it comes to showing our Loading View in full width.
It doesn’t have the helper class .spanSizeLookup as the Grid Layout has. So we need to add the following code to our RecyclerView’s Adapter:
And run it!
You can find the final project here
If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!