I’ve been working on a small news feed component for a project recently and wanted to find a way to auto-load posts while the user scrolls through a list. After a bit of researching it turned out RecyclerView doesn’t really support this behavior out of the box, so I did a little more digging. There were a few methods that involved creating a custom view or extending AbsListView.OnScrollListener. In the end most of these methods ultimately relied on using OnScrollListener.
The desired behavior is pretty simple. You’ve probably seen it in a lot of apps that have a news feed, like Facebook for example. As you scroll down your news feed the list continues loading new content without any button presses or gestures needed. This pattern is a lot more intuitive than the press to load more patterns that were more common/popular in the past.
RecyclerView and OnScrollListener
Implementing this functionality isn’t actually too hard either. You will need two things though, a variable for loading and a LayoutManager that supports findFirstVisibleItemPosition. For ease of explanation we’ll just assume that LinearLayoutManager is being used. Here’s an example of a Fragment that contains RecyclerView:
You add together the visibleItemCount and the firstVisible position from the LayoutManager and then check if that is equal or above the totalItemCount. If these conditions are met you switch loading to true and then do whatever you need to do to load new items(make API calls etc.). Somewhere in your loading logic, you’ll need to switch loading back to false. This is just to prevent multiple/continuous loading calls.
Room for Improvement
Again this is just a basic example, you might want to change the threshold around so you start loading from 5 items above the end of your list. You’ll probably also want to add some kind of footer as well to make things smoother for the user. You could also turn this logic into a custom view(I ended up doing this), or create an RxObservable for the logic. The other week I wrote another post about using Firebase JobDispatcher for recurring tasks in Android, if you’re interested be sure to check it out.