Infinite scroll is the most prevalant designs of all times. The reason of it’s meteoric rise is that it actually works. In this article, we will learn how to implement one in Android. I’ll be creating a very simple app like the below gif. It scrolls upto few number, then fetches another set of data and then is scrollable again. Checkout the below the gif:
Let’s go through the below steps to create this app:
Step 1 - Creating layout for list item
Below is the item layout for the list.
recycler_row.xml
Step 2 - Creating Recycler view
Since we are dealing with only one activity, I am putting the Recycler view in that Activity.
activity_main.xml
Step 3 - Creating Recycler view adapter
To populate data in the recycler view, we will create a recyler view adapter. Here is how it looks:
RecyclerAdapter.kt
Step 4 - Create function that provides data
Let’s now create a function which when called, appends 30 data items to an existing list. We are emulating a network call, which brings in an additional data and appends it to an existing data-source.
Find this and lot of other recipes written in Kotlin in my book Kotlin Programming Cookbook
Step 5 - Setting up the RecyclerView in the activity
Let’s now create a function which when called, appends 30 data items to an existing list. We are emulating a network call, which brings in an additional data and appends it to an existing data-source.
Since we have to intercept when the user has reached the bottom of the list, we have added a ScrollListener . We have overridden the onScroll method, and we are using the canScrollVertically method. The canScrollVertically method was added in API level 14, and it is used to check whether this view can be scrolled vertically in a certain direction. It takes an integer argument (negative to check scrolling up and positive to check scrolling down) and returns a boolean ( true if possible, false if not). In our example, we have supplied a positive integer, which will return true if the view can be scrolled down and false if it can’t be. If it can’t be further scrolled down (meaning that the data is exhausted), we will add data to the list and update the list by calling the notifyItemRangeInserted method of the adapter.