RecyclerView essentials
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
areContentsTheSamewrong 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:
onCreateViewHolderinflates a layout and wraps it in aViewHolder. It is called only when no reusable holder of that view type is available.onBindViewHoldercopies 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.- When a holder scrolls off-screen,
RecyclerViewfirst 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 theRecycledViewPool(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.
| Concept | What it controls |
|---|---|
DiffUtil.ItemCallback | How the adapter decides "same item" and "same content" |
setHasStableIds(true) + getItemId | Lets RecyclerView match items by id when you call notifyDataSetChanged; not needed for DiffUtil animations |
getItemViewType | Which layout to inflate; one adapter, many row shapes |
payloads in onBindViewHolder | Optional data describing a change, so you can update only part of the row |
submitList | The 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
ListAdapterwrapsAsyncListDiffer, which runsDiffUtil.calculateDiffon a background thread;submitListis how you give it data, andcurrentListis what it shows.DiffUtil.ItemCallbackrequires two methods:areItemsTheSame(identity, usually anid) andareContentsTheSame(are the visible contents equal; a data class==is usually fine).areContentsTheSameis only called for pairs whereareItemsTheSamereturnedtrue. IfareItemsTheSamecompares whole objects, every edit looks like remove plus insert.submitListwith the same list instance does nothing. Always submit a new list; never mutate the list you already submitted.- DiffUtil already reports moves, so
ListAdapteranimates moves without stable IDs. Stable IDs help when you callnotifyDataSetChanged()with a plain adapter. CallsetHasStableIds(true)before the adapter is attached. - View types let one adapter render multiple item layouts;
getItemViewTypereturns anInt, andonCreateViewHolderswitches on it. Each type has its own pool. - Payloads: override
getChangePayloadin theItemCallback(or callnotifyItemChanged(position, payload)), then override the 3-argumentonBindViewHolder. An emptypayloadslist 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 inonBindViewHolder. - Read items with
getItem(position)(orcurrentList), not from a separate list you keep yourself, which can differ from what the adapter is showing. - Call
submitListon 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
ViewBindingreference inonDestroyViewto avoid leaking the old view tree (relevant when the RecyclerView is inside a bound layout). - If you enable stable IDs,
getItemIdmust return a unique, unchanging id. The default returnsRecyclerView.NO_IDfor 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
onBindViewHolderis abstract and must always be overridden. The 3-argument version is optional; it falls back to the full bind wheneverpayloadsis empty or contains something it does not understand. getChangePayloadis called only whenareItemsTheSameis true andareContentsTheSameis 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
ListAdapteranimates correctly without them. findViewByIdis used here for brevity; in a ViewBinding project you would hold anItemBodyBindingin 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
- 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
CheckBoxstate was set totrueinonBindViewHolderbut never reset tofalse, so a recycled ViewHolder carried the old checked state into the next item.
- 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.isReadinstead of only setting it totrue. - 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
onBindViewHolderreset all mutable state?"
- 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
onCreateViewHolderandonBindViewHoldercalls on the main thread after eachsubmitList. - Cause:
areItemsTheSamewas written asoldItem == 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.
- Reproduced with a fake repository that changes one like count per second.
- Changed
areItemsTheSameto compareid, and kept data class equality inareContentsTheSame. - Added
getChangePayloadfor 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.
submitListignores 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 examplelist.toMutableList().apply { add(item) }. - Calling notifyDataSetChanged on a ListAdapter. It throws away DiffUtil's work, rebinds everything and disables item animations. Let
submitListdispatch 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
ViewinsideonBindViewHolderdefeats recycling and causes jank on long lists. Inflate only inonCreateViewHolder.
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.
- Add a
TYPE_HEADERconstant (value0) and rename the existing type toTYPE_ITEM(value1). - Add a
val isHeader: Booleanfield to yourItemdata class. - Override
getItemViewTypeto returnTYPE_HEADERwhenisHeaderistrue, otherwiseTYPE_ITEM. - In
onCreateViewHolder, inflateR.layout.item_headerforTYPE_HEADERandR.layout.item_bodyforTYPE_ITEM. Create a separateViewHoldersubclass for each type if the views differ. - In
onBindViewHolder, bind the header layout differently (set bold text, no click listener) and the body layout as before. - 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.