Home Android & Kotlin Books Android Apprentice

7
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 and MainFragment.kt: Located in the java folder.
  • activity_main.xml and content_main.xml: Located in the res\layout folder.

Kotlin (.kt) files drive the logic of your app. MainActivity.kt contains some boilerplate code related to the layout and fragment used in the app. MainFragment.kt is a Fragment used within MainActivity.kt. The Fragment is where your Views will be placed. Don’t worry too much about what a Fragment is at the moment. You will learn more about them in Chapter 11.

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

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

There’s a TextView in the middle of the layout. You’re going to replace the TextView with a RecyclerView.

Adding a RecyclerView

At the moment, the biggest feature missing from ListMaker is lists! There isn’t any way to show a list, let alone the master list of lists. It’s like Inception, but…Listception instead. You’ll fix that by adding a RecyclerView.

Behold, the RecyclerView!
Xowovf, tlo SockmposQaic!

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 using ViewBinding

For this app, you’re going to access views from your layout differently. Using a technique called ViewBinding. ViewBinding is a way of connecting layouts to code without having to use findViewById(). Let’s see how this works.


android {

  ...

  buildFeatures {
    viewBinding true
  }
}
private lateinit var binding: MainFragmentBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
  binding = MainFragmentBinding.inflate(inflater, container, false)
  return binding.root
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
  binding = MainFragmentBinding.inflate(inflater, container, false)

  // 1
  binding.listsRecyclerview.layoutManager = LinearLayoutManager(requireContext())

  // 2
  binding.listsRecyclerview.adapter = ListSelectionRecyclerViewAdapter()

  return binding.root
}

Setting up a RecyclerView Adapter

Right-click ui.main 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(val binding: ListSelectionViewHolderBinding) : RecyclerView.ViewHolder(binding.root) {
}
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 binding = ListSelectionViewHolderBinding.inflate(LayoutInflater.from(parent.context), parent, false)
  // 2
  return ListSelectionViewHolder(binding)
}

Binding data to your ViewHolder

With the ViewHolder created, you have to bind the list titles to it. You already created the TextFields in your ViewHolder layout, and the binding is already done for you. All that’s left is to assign the right value to each TextView.

override fun onBindViewHolder(holder: ListSelectionViewHolder, position: Int) {
  holder.binding.itemNumber.text = (position + 1).toString()
  holder.binding.itemString.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.

Key Points

You’ve just completed your first steps to build ListMaker! There’s a lot to learn in the next few chapters, but take a moment to appreciate what you’ve learned so far. You’ve learned:

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.