RecyclerView essentials

Learn how Android RecyclerView recycles ViewHolders, how ListAdapter and DiffUtil compute minimal updates, and how to fix the recycled-state bug. About 25 minutes.

Why it matters

  • RecyclerView is still the list component in many production Android apps; you will likely maintain it even in Compose-first teams.
  • Interviewers at mid and senior levels ask about recycling, DiffUtil, and the recycled-state bug to check you understand the mechanism, not just the API.
  • Getting areContentsTheSame wrong causes either missed updates or excessive rebinds, both visible to users as flicker or jank.
  • Correct DiffUtil callbacks and payloads are the difference between a list that animates smoothly and one that flickers on every refresh.

The simple explanation

  • Think of a library with a fixed number of display stands (say 5).
  • The catalog has 500 books, but only 5 stands exist.
  • When a reader walks past, the librarian takes the book off the stand, shoves it back into the shelf, and puts the next book on.
  • The stand is the ViewHolder; the book is the data item.
  • If the librarian forgets to remove the old book's bookmark, the next reader sees a wrong page number. That is the recycled-state bug.

RecyclerView is a ViewGroup that shows a scrolling list. It does not create a View for every item. It creates roughly enough ViewHolder objects to fill the screen plus a few extras and recycles them as the user scrolls.

The lifecycle per item is:

  1. onCreateViewHolder inflates a layout and wraps it in a ViewHolder. It is called only when no reusable holder of that view type is available.
  2. onBindViewHolder copies data from the item into the holder's views. It is called when a holder is shown for a position, including when it is reused, and when an item changes.
  3. When a holder scrolls off-screen, RecyclerView first keeps it in a small view cache (2 by default) that can be shown again for the same position without rebinding. Older holders go to the RecycledViewPool (up to 5 per view type by default), and a holder from the pool is always rebound before use.

ListAdapter (part of androidx.recyclerview:recyclerview) wraps AsyncListDiffer, which runs DiffUtil.calculateDiff on a background thread. You call submitList(newList) and the adapter figures out which items were added, removed, or changed, then dispatches granular notifyItem* calls on the main thread.

ConceptWhat it controls
DiffUtil.ItemCallbackHow the adapter decides "same item" and "same content"
setHasStableIds(true) + getItemIdLets RecyclerView match items by id when you call notifyDataSetChanged; not needed for DiffUtil animations
getItemViewTypeWhich layout to inflate; one adapter, many row shapes
payloads in onBindViewHolderOptional data describing a change, so you can update only part of the row
submitListThe single entry point; runs diff off the main thread

The recycled-state bug is a common RecyclerView defect: a holder is reused but still shows a checked CheckBox, a half-finished ProgressBar, or a selected TextView from the previous item. The fix is to reset every piece of mutable state in onBindViewHolder before applying the new data.

Notes

  • ListAdapter wraps AsyncListDiffer, which runs DiffUtil.calculateDiff on a background thread; submitList is how you give it data, and currentList is what it shows.
  • DiffUtil.ItemCallback requires two methods: areItemsTheSame (identity, usually an id) and areContentsTheSame (are the visible contents equal; a data class == is usually fine).
  • areContentsTheSame is only called for pairs where areItemsTheSame returned true. If areItemsTheSame compares whole objects, every edit looks like remove plus insert.
  • submitList with the same list instance does nothing. Always submit a new list; never mutate the list you already submitted.
  • DiffUtil already reports moves, so ListAdapter animates moves without stable IDs. Stable IDs help when you call notifyDataSetChanged() with a plain adapter. Call setHasStableIds(true) before the adapter is attached.
  • View types let one adapter render multiple item layouts; getItemViewType returns an Int, and onCreateViewHolder switches on it. Each type has its own pool.
  • Payloads: override getChangePayload in the ItemCallback (or call notifyItemChanged(position, payload)), then override the 3-argument onBindViewHolder. An empty payloads list means you must do a full bind.
  • The recycled-state bug: a reused ViewHolder still shows visual state (checked CheckBox, visibility, listeners, a running image load) from the previous item; set every property in onBindViewHolder.
  • Read items with getItem(position) (or currentList), not from a separate list you keep yourself, which can differ from what the adapter is showing.
  • Call submitList on the main thread. Some paths, such as submitting to an empty adapter, update the adapter synchronously on the calling thread.
  • In a Fragment, clear the ViewBinding reference in onDestroyView to avoid leaking the old view tree (relevant when the RecyclerView is inside a bound layout).
  • If you enable stable IDs, getItemId must return a unique, unchanging id. The default returns RecyclerView.NO_ID for every item, which breaks item tracking.

Code example

This shows a production-style ListAdapter with a DiffUtil.ItemCallback, a change payload, two view types, and a full bind that sets every property.

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
 
data class Item(val id: Long, val type: Int, val text: String, val isRead: Boolean)
 
private const val TYPE_TITLE = 0
private const val TYPE_BODY = 1
private const val PAYLOAD_READ = "read"
 
private val ItemDiff = object : DiffUtil.ItemCallback<Item>() {
    override fun areItemsTheSame(oldItem: Item, newItem: Item) = oldItem.id == newItem.id
    override fun areContentsTheSame(oldItem: Item, newItem: Item) = oldItem == newItem
 
    // Only isRead changed: ask for a partial bind instead of a full one
    override fun getChangePayload(oldItem: Item, newItem: Item): Any? =
        if (oldItem.copy(isRead = newItem.isRead) == newItem) PAYLOAD_READ else null
}
 
class ItemAdapter : ListAdapter<Item, ItemAdapter.VH>(ItemDiff) {
 
    class VH(view: View) : RecyclerView.ViewHolder(view) {
        val text: TextView = view.findViewById(R.id.text)
        val read: CheckBox? = view.findViewById(R.id.read) // only in item_body
    }
 
    override fun getItemViewType(position: Int): Int = getItem(position).type
 
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        val layout = if (viewType == TYPE_TITLE) R.layout.item_title else R.layout.item_body
        val v = LayoutInflater.from(parent.context).inflate(layout, parent, false)
        return VH(v)
    }
 
    // Full bind: assign every property so nothing leaks from the previous item
    override fun onBindViewHolder(holder: VH, position: Int) {
        val item = getItem(position)
        holder.text.text = item.text
        holder.read?.isChecked = item.isRead
    }
 
    override fun onBindViewHolder(holder: VH, position: Int, payloads: List<Any>) {
        if (payloads.isNotEmpty() && payloads.all { it == PAYLOAD_READ }) {
            holder.read?.isChecked = getItem(position).isRead   // partial bind
        } else {
            onBindViewHolder(holder, position)                  // full bind
        }
    }
}
  • The 2-argument onBindViewHolder is abstract and must always be overridden. The 3-argument version is optional; it falls back to the full bind whenever payloads is empty or contains something it does not understand.
  • getChangePayload is called only when areItemsTheSame is true and areContentsTheSame is false. Returning a payload means the row is updated in place without the default change animation.
  • No stable IDs here: DiffUtil computes inserts, removes and moves itself, so ListAdapter animates correctly without them.
  • findViewById is used here for brevity; in a ViewBinding project you would hold an ItemBodyBinding in the ViewHolder instead.

Run the idea in plain Kotlin

class ViewHolder(val id: Int, var boundText: String = "") {
  var recycled = false
  fun reset() { recycled = false; boundText = "" }
}

class RecyclerPool(private val maxSize: Int) {
  private val available = ArrayDeque<ViewHolder>()
  private val created = ArrayDeque<ViewHolder>()
  private var nextId = 0

  fun obtain(): ViewHolder {
      val vh = if (available.isNotEmpty()) available.removeFirst() else {
          val v = ViewHolder(nextId++)
          created.addLast(v)
          v
      }
      vh.reset()
      return vh
  }

  fun recycle(vh: ViewHolder) {
      vh.recycled = true
      available.addLast(vh)
  }

  fun totalCreated(): Int = created.size
}

fun main() {
  val pool = RecyclerPool(maxSize = 3)
  val items = listOf("Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot")
  val visible = 3

  for (start in 0..(items.size - visible)) {
      val end = start + visible
      val holders = (start until end).map { pool.obtain() }
      for (i in holders.indices) {
          holders[i].boundText = items[start + i]
      }
      println("Scroll pos " + start + ": showing " + items.subList(start, end).joinToString(", "))
      println("  Holders used: " + holders.map { "VH#" + it.id }.joinToString(", "))
      for (h in holders) pool.recycle(h)
  }
  println("Total ViewHolders ever created: " + pool.totalCreated())
}

Expected output: four scroll positions, from Scroll pos 0: showing Alpha, Bravo, Charlie to Scroll pos 3: showing Delta, Echo, Foxtrot, each with Holders used: VH#0, VH#1, VH#2, and finally Total ViewHolders ever created: 3. Six items were shown with only three holders.

In production

Checkbox stays checked after scroll
  • Users reported that checking a "read" checkbox on a list item would show as checked on a completely different item after scrolling.
  • Support tickets increased; crash-free rate was unaffected because no exception was thrown.
  • Cause: the CheckBox state was set to true in onBindViewHolder but never reset to false, so a recycled ViewHolder carried the old checked state into the next item.
The fix
  • Team reproduced by scrolling fast on a long list on a mid-range device.
  • Changed the bind code to always assign holder.checkbox.isChecked = item.isRead instead of only setting it to true.
  • Added a Robolectric test that binds item A (checked) to a holder, binds item B (unchecked) to the same holder, and asserts the checkbox is unchecked.
  • Added a code-review checklist item: "does onBindViewHolder reset all mutable state?"
Flicker and jank on every refresh
  • Users on mid-range devices reported that the whole feed blinked and stuttered every time it refreshed, even when only a like count changed.
  • A system trace showed many onCreateViewHolder and onBindViewHolder calls on the main thread after each submitList.
  • Cause: areItemsTheSame was written as oldItem == newItem. Any change in a post made DiffUtil treat it as a different item, so it reported a remove plus an insert. RecyclerView ran remove and add animations and created and bound new holders for those rows.
The fix
  • Reproduced with a fake repository that changes one like count per second.
  • Changed areItemsTheSame to compare id, and kept data class equality in areContentsTheSame.
  • Added getChangePayload for the like count, so only the counter text is updated in place.
  • Verified in a new trace that a like change binds one row with a payload and inflates nothing. Added a unit test for the ItemCallback.

Common mistakes

  • Not resetting state in onBindViewHolder. A recycled ViewHolder keeps the previous item's checkbox, visibility, listener or image. Always assign a definite value to every mutable property from the new item, not just the ones that changed.
  • Comparing whole objects in areItemsTheSame. Identity must be the id. Comparing everything turns every edit into remove plus insert, with flicker and extra binding.
  • Mutating the submitted list and submitting it again. submitList ignores the same list instance, so the UI does not update. Even if it did, the old and new lists would be identical and the diff would find nothing. Submit a new list, for example list.toMutableList().apply { add(item) }.
  • Calling notifyDataSetChanged on a ListAdapter. It throws away DiffUtil's work, rebinds everything and disables item animations. Let submitList dispatch the changes.
  • Calling submitList off the main thread. It is meant for the main thread; some paths update the adapter synchronously on the calling thread, which can crash. Collect your flow on the main thread and submit there.
  • Creating views in onBindViewHolder. Inflating or allocating a new View inside onBindViewHolder defeats recycling and causes jank on long lists. Inflate only in onCreateViewHolder.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How does RecyclerView recycling work?”

“What do ListAdapter and DiffUtil do?”

“What are view types and when do you need them?”

“What is the recycled-state bug and how do you prevent it?”

Quiz

What does ListAdapter.submitList() do?

What is the recycled-state bug?

In a DiffUtil.ItemCallback, what should areItemsTheSame compare?

What does a non-empty payloads list in onBindViewHolder mean?

0 of 4 answered

Mini task

Add a second view type to an existing ListAdapter

You have a ListAdapter that renders a single item layout (a TextView with a title). Add a header view type that shows a bold, larger title with no click listener.

  1. Add a TYPE_HEADER constant (value 0) and rename the existing type to TYPE_ITEM (value 1).
  2. Add a val isHeader: Boolean field to your Item data class.
  3. Override getItemViewType to return TYPE_HEADER when isHeader is true, otherwise TYPE_ITEM.
  4. In onCreateViewHolder, inflate R.layout.item_header for TYPE_HEADER and R.layout.item_body for TYPE_ITEM. Create a separate ViewHolder subclass for each type if the views differ.
  5. In onBindViewHolder, bind the header layout differently (set bold text, no click listener) and the body layout as before.
  6. Add a header item to your list and call submitList.

Done condition: Scrolling the list shows the header with a different layout (bold, larger text), the header does not respond to item clicks, and the body items still work as before. No ClassCastException or blank rows appear.