Employing RecyclerView

If you have spent much time with Android devices and apps, no doubt that you will have seen apps that show lists or grids of stuff: contacts, songs, movies, books, to-do items, etc.

If the app was written in 2015 or later, there is a very good chance that it uses RecyclerView for those lists and grids. In this chapter, we will explore what RecyclerView is and how you can use it for your own collections of data.

Recap: Layouts vs. Adapter-Based Containers

As we saw back in the chapter on ConstraintLayout, there are two major types of ViewGroup implementations:

Mostly, ConstraintLayout is for the first scenario. You know that you will have a certain set of widgets that you want to appear, and you need to size and position them. ConstraintLayout — and the legacy containers, like LinearLayout — excel at this role.

However, quite frequently, we have collections of stuff to display. We might know what sorts of stuff would be in the collection (contacts, songs, movies, books, to-do items, etc.). But we do not know how big the collection will be. Perhaps when we first run the app, the collection will be empty. Over time, the collection might grow. If we are reusing data from other places, such as the user’s contact manager, there might be lots of data from the outset. We just do not know.

ConstraintLayout would be useful for displaying an individual item out of that collection of stuff. However, trying to use ConstraintLayout and ScrollView to handle an arbitrary-sized collection would be really painful.

Fortunately, we have options.

The original solution for this sort of problem was the AdapterView family of classes, notably ListView. AdapterView worked but was fairly inflexible. RecyclerView was created as an alternative, and it is the dominant solution for this problem today. We will discuss ListView and the rest of AdapterView towards the end of the chapter, but outside of certain scenarios, your focus nowadays should be on RecyclerView.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.