Android RecyclerViews 101

RecyclerViews for Android are the natural evolution of the ListView. They are cleaner, easier to use, and always enforce view recycling. Use them whenever you want to display data with a set of common views that can be reused for efficiency and to replace ListViews and GridView.

This tutorial will teach you how to use a RecyclerView to display a list of Strings.

Setup for this tutorial included the creation of a new project using the [Blank Activity] template in Android Studio. The resulting project includes: MainActivity.class.

Adding the Dependencies

The RecyclerView class must be manually included in your projects in order to use it. Why? I’m not sure, but maybe they just like us to have extra steps to do. Let’s add it.

Go into your build.gradle file—the one for your app, not the project. (The correct one for your app will say “android” somewhere in it.) Add this line:

compile 'com.android.support:recyclerview-v7:21.0.+'

on a new line inside the dependencies section. ReSync gradle… and Boom! We can use it!

Adding the LayoutManager

Using one of these provided LayoutManagers allows us to easily replace ListViews and GridViews :). For this tutorial, we will use a LinearLayoutManager setup to display items vertically—like a ListView.

Next, let’s make a simple layout that includes a TextView for displaying each item in our list, and an ImageView that displays the launcher icon. (The ImageView is just to show that we can have multiple subviews for each item.)

The Adapter class requires us to have an extension of RecyclerView.ViewHolder for recycling purposes. This ViewHolder is meant to be an accessor for all the subviews of each item. In our example, we will only require a TextView, but more complex scenarios could include any number of TextViews, ImageViews, or other Views.

So inside of RecyclerViewStringListAdapter, let’s create an inner class that extends RecyclerView.ViewHolder and grabs a reference to our TextView that we will use to display our String and the ImageView (in case we want to change the image for each item).

4 more things!
In this adapter we are required to Override onCreateViewHolder, onBindViewHolder, and getItemCount. We should also add a constructor that we can use to pass in the data we want the adapter to use.

First, add a member variable and a constructor that takes in a list of Strings and keeps the reference:

Finally, we have the onBindViewHolder. This method is for populating all views in the provided ViewHolder that will be placed at the provided position. For us it’s simple: set the text on the TextView. We could also change the image here if we really wanted to.