Home Android & Kotlin Books Android Apprentice

RecyclerViews Written by Darryl Bayliss

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

In this chapter, you’ll begin to build ListMaker. An app to help organize all of your to-do lists in one handy place.

Lists are a common visual design pattern in apps, they allow developers to group collections of information together. They also allow users to scroll through and interact with each item in the list.

These apps all use RecyclerView
These apps all use RecyclerView

An item in a list can range from a line of text to more complex content like a video with comments below it — a common style used in most social media apps.

In Android development, you implement lists using a class named RecyclerView. As part of this chapter, you’ll learn how to:

  1. Get started with RecyclerView.
  2. Set up a RecyclerView Adapter to populate a list with data.
  3. Set up a ViewHolder to handle the Layout of each item in the list.

Getting started

If you’ve been following along with your own project, open it. If not, don’t worry. Locate the projects folder for this chapter and open the Listmaker app inside the starter folder. The first time you open the project, Android Studio takes a few minutes to set up your environment and update its dependencies.

With the Android Studio project open, examine the project structure. In particular, look at the following files:

  • MainActivity.kt: Located in the java folder.
  • activity_main.xml and content_main.xml: Located in the layout folder.

Kotlin (.kt) files drive the logic of your app. MainActivity.kt contains some familiar-looking boilerplate code related to the Activity and Menu lifecycles.

In previous chapters, you used a single Layout file to build the user interface. In this project, there are two Layout files: activity_main.xml and content_main.xml.

Why are there two?

Open activity_main.xml. With the Design view open, examine the Component Tree:

There’s a Toolbar to display menu items, as well as a FloatingActionButton. A Floating Action Button (or FAB) works similar to a button, the difference is a FAB also adheres to Googles Material Design guidelines. Don’t worry about these guidelines for now, you’ll learn more about them in Chapter 12.

Keep scanning, and you’ll see a component named include. This is where content_main.xml comes into play: The activity_main.xml Layout includes the Layout defined in content_main.xml. This is how you use both Layouts in the Activity.

While it looks strange to take this approach, it’s useful when using a Layout in multiple places within your app. It also helps when the Layout is complex enough to benefit from being split into multiple files.

Open content_main.xml and review the component tree for the layout:

It contains something called a Nav Host Fragment. We won’t touch upon these in the book, for now you’re going to replace the nav host fragment with a RecyclerView. You’ll do that in the next part.

Adding a RecyclerView

Did you notice that something important is missing from ListMaker? That’s right! It’s missing lists. At the moment, there isn’t any way to show a list, let alone the master list of lists. It’s like Inception, but…Listception instead.

Behold, the RecyclerView!
Porizy, mxe CawhmvusTaeh!

The components of a RecyclerView

The RecyclerView lets you display large amounts of data in a list format. Each piece of data is treated as an item within the RecyclerView. In turn, each of these items makes up the entire contents of the RecyclerView.

Hooking up a RecyclerView

Open MainActivity.kt and create a property to hold a RecyclerView, just above onCreate(savedInstanceState: Bundle?):

lateinit var listsRecyclerView: RecyclerView
// 1
listsRecyclerView = findViewById(R.id.lists_recyclerview)
// 2
listsRecyclerView.layoutManager = LinearLayoutManager(this)
// 3
listsRecyclerView.adapter = ListSelectionRecyclerViewAdapter()

Setting up a RecyclerView Adapter

Right-click com.raywenderlich.listmaker in the Project navigator. In the floating options that appear, hover over New. In the next set of options that appear, click Kotlin File/Class.

class ListSelectionViewHolder(itemView: View) :
  RecyclerView.ViewHolder(itemView) {
class ListSelectionRecyclerViewAdapter :
  RecyclerView.Adapter<ListSelectionViewHolder>() {

Filling in the blanks

With the basics of the RecyclerView Adapter and ViewHolder set up, it’s time to put the pieces together. First, you need content for the RecyclerView to show. For now, you’ll add some mock titles to show off the RecyclerView.

val listTitles = arrayOf("Shopping List", "Chores", "Android Tutorials")
override fun getItemCount(): Int {
  return listTitles.size

Creating the ViewHolder

In the Project navigator on the left, right-click on the layout folder and create a new Layout resource file:

override fun onCreateViewHolder(parent: ViewGroup,
             viewType: Int): ListSelectionViewHolder {
    // 1          
    val view = LayoutInflater.from(parent.context)
    // 2          
    return ListSelectionViewHolder(view)
> **Note**: `LayoutInflater` is a system utility used to instantiate (or "inflate") a layout XML file into its corresponding View objects.

Binding data to your ViewHolder

With the ViewHolder created, you have to bind the list titles to it. To do this, you need to know what Views to bind your data to. You already created the TextFields in your ViewHolder Layout, but you haven’t yet referenced these in code yet.

  val listPosition = itemView.findViewById(R.id.itemNumber) as TextView

  val listTitle = itemView.findViewById(R.id.itemString) as TextView
override fun onBindViewHolder(holder: ListSelectionViewHolder, position: Int) {

    holder.listPosition.text = (position + 1).toString()
    holder.listTitle.text = listTitles[position]

The moment of truth

Finally! You can see the fruits of your labors. Click the Run App button at the top of Android Studio and see what happens.

Where to go from here?

There are many moving pieces required to use RecyclerView to display a list of data. However, don’t be afraid to use them, they’re an essential construct for creating Android apps that provide fluid and intuitive user experiences. They are as common as Buttons and TextViews.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.