4.3 Implementation of a Recycler View

Key classes

Several different classes work together to build your dynamic list.

  • RecyclerView is the ViewGroup that contains the views corresponding to your data. It's a view itself, so you add RecyclerView into your layout the way you would add any other UI element.

  • Each individual element in the list is defined by a view holder object. When the view holder is created, it doesn't have any data associated with it. After the view holder is created, the RecyclerView binds it to its data. You define the view holder by extending RecyclerView.ViewHolder.

  • The RecyclerView requests those views, and binds the views to their data, by calling methods in the adapter. You define the adapter by extending RecyclerView.Adapter.

  • The layout manager arranges the individual elements in your list. You can use one of the layout managers provided by the RecyclerView library, or you can define your own. Layout managers are all based on the library's LayoutManager abstract class.

Steps for implementing your RecyclerView

  • Design how each element in the list is going to look and behave in some layout file. Based on this design, extend the ViewHolder class. Your version of ViewHolder provides all the functionality for your list items. Your view holder is a wrapper around a View, and that view is managed by RecyclerView.

  • Define the Adapter that associates your data with the ViewHolder views.

Implementing your adapter and view holder

When you define your adapter, you need to override three key methods:

  • onCreateViewHolder(): RecyclerView calls this method whenever it needs to create a new ViewHolder. The method creates and initializes the ViewHolder and its associated View, but does not fill in the view's contents—the ViewHolder has not yet been bound to specific data.

  • onBindViewHolder(): RecyclerView calls this method to associate a ViewHolder with data. The method fetches the appropriate data and uses the data to fill in the view holder's layout. For example, if the RecyclerView displays a list of names, the method might find the appropriate name in the list and fill in the view holder's TextView widget.

  • getItemCount(): RecyclerView calls this method to get the size of the data set. For example, in an address book app, this might be the total number of addresses. RecyclerView uses this to determine when there are no more items that can be displayed.

First we introduce the data model that will be used for the rest of this lesson:

data class Book(var bookName: String, var author: String, val publisher: String)

Here's a typical example of a simple adapter with a nested ViewHolder that displays a list of data. In this case, the RecyclerView displays a simple list of Book elements. The adapter is passed an array of books, containing the data needed for the ViewHolder elements:

class CustomAdapter(private val dataSet: List<Book>) :
        RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val bookName: TextView = view.findViewById(R.id.book_name)
        val author: TextView = view.findViewById(R.id.author)
        val publisher: TextView = view.findViewById(R.id.publisher)

    // Create new views (invoked by the layout manager)
    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
        // Create a new view, which defines the UI of the list item
        val view = LayoutInflater.from(viewGroup.context)
                .inflate(R.layout.book_row_item, viewGroup, false)
        return ViewHolder(view)

    // Replace the contents of a view (invoked by the layout manager)
    override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.bookName.text = dataSet[position].bookName
        viewHolder.author.text = dataSet[position].author
        viewHolder.publisher.text = dataSet[position].publisher

    // Return the size of your dataset (invoked by the layout manager)
    override fun getItemCount() = dataSet.size

The snippet above can be tailored to your specific needs in terms of whatever data you are trying to display as a list with RecyclerView!

The layout for the each view item is defined in an XML layout file, similarly as we do for activities. In this case, the app has a book_row_item.xml file like this:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"


            app:layout_constraintTop_toTopOf="parent" />

            app:layout_constraintTop_toBottomOf="@id/book_name" />

            app:layout_constraintTop_toBottomOf="@id/author" />

In this case, I use a new ViewGroup called CardView to build beautiful row items for our RecyclerView! CardView is an extended version of Framelayout which can be used to show items inside the card format. With the help of CardView, we can add radius, elevation to our items of RecyclerView. CardView gives a rich look and feel to our list of data. Check this out to learn more!

Integrating RecyclerView with Activity

1. We can add RecyclerView to our layout file as such:

<?xml version="1.0" encoding="utf-8"?>
<!-- A RecyclerView with some commonly used attributes -->

2. Integrate it into activity:

class MyActivity : AppCompatActivity() {
    private lateinit var recyclerView : RecyclerView

    override fun onCreate(Bundle savedInstanceState) {
        recyclerView = findViewById<RecyclerView>(R.id.my_recycler_view)

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView

        // use a linear layout manager
        recyclerView.layoutManager = LinearLayoutManager(this)

        // create dataset, format should match what you specified 
        // in the MyAdapter object
        var myDataset = mutableListOf<Book>()
        // Populate your myDataset with your data
        recyclerView.adapter = CustomAdapter(myDataset)
    // ...

Other LayoutManagers

In MyActivity.kt, I simply used a LinearLayoutManager to arrange our RecyclerView items. LinearLayoutManager arranges the items in a one-dimensional list but there are other managers available!

  • GridLayoutManager arranges all items in a two-dimensional grid:

    • If the grid is arranged vertically, GridLayoutManager tries to make all the elements in each row have the same width and height, but different rows can have different heights.

    • If the grid is arranged horizontally, GridLayoutManager tries to make all the elements in each column have the same width and height, but different columns can have different widths.

  • StaggeredGridLayoutManager is similar to GridLayoutManager, but it does not require that items in a row have the same height (for vertical grids) or items in the same column have the same width (for horizontal grids). The result is that the items in a row or column can end up offset from each other.

  • One can also create a customized Layout Manager!

This is the bare bone code that is needed to create a recycler view list in Android. In the next section, we’ll be delving into an example of adding touch input.

Last updated