skip to content

In RecyclerView, what does onCreateViewHolder do versus onBindViewHolder, and why must every bind reset each view it sets?

level: juniorimportance: must knowfreq 80%

answer

  1. inflate once, fill many times
  2. holders come back dirty
  3. pool holders always rebound
  4. both branches of every if
  5. getBindingAdapterPosition, not the captured position

basics

~20 s

onCreateViewHolder inflates a row layout and caches its child views in a new ViewHolder; onBindViewHolder writes one item's data into an existing, possibly recycled holder. A recycled holder keeps the last item's state, so each bind must set every view.

solid answer

~40 s

`onCreateViewHolder(parent, viewType)` runs only when RecyclerView needs a holder of that view type and has none to reuse: it inflates the layout and caches child references. `onBindViewHolder(holder, position)` runs every time a holder is shown for an item. Holders taken from the `RecycledViewPool` still carry the previous item's text, visibility and images, so a bind that sets a view in one branch only (show the downloaded badge, never hide it) leaks state into the next row. The bind should also never capture `position` in a listener: RecyclerView does not rebind when an item merely moves, so read `getBindingAdapterPosition()` at click time and check for `NO_POSITION`.

code

kotlin · 24 lines
kotlin
class BookViewHolder(itemView: View, onClick: (Int) -> Unit) :
    RecyclerView.ViewHolder(itemView) {
    val title: TextView = itemView.findViewById(R.id.title)
    val badge: ImageView = itemView.findViewById(R.id.downloaded_badge)

    init {
        itemView.setOnClickListener {
            val pos = bindingAdapterPosition
            if (pos != RecyclerView.NO_POSITION) onClick(pos)
        }
    }
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookViewHolder {
    val view = LayoutInflater.from(parent.context)
        .inflate(R.layout.item_book, parent, false)
    return BookViewHolder(view) { pos -> onBookClick(books[pos]) }
}

override fun onBindViewHolder(holder: BookViewHolder, position: Int) {
    val book = books[position]
    holder.title.text = book.title
    holder.badge.visibility = if (book.isDownloaded) View.VISIBLE else View.GONE
}

go deeper

for a junior

Say which callback inflates and which fills data, and that a recycled holder still shows the previous item until you overwrite every view.

for a middle

Explain the offscreen view cache versus the RecycledViewPool, why pool holders are always rebound, and why getBindingAdapterPosition replaced a captured position.

for a senior

Diagnose stale-row bugs from a review: one-branch visibility, a captured position, image loads never cleared in onViewRecycled, row state kept only in views.

for a principal

Set a team review rule for adapters: binds are total functions of the item, listeners live in creation, and heavy per-row resources are released when the holder is recycled.

## Two callbacks, two jobs A `RecyclerView.Adapter` has two required callbacks that people often blur together, and most "wrong data in a row" bugs come from that blur. - **`onCreateViewHolder(parent, viewType)`** builds a new `ViewHolder`: it inflates the row layout for that **view type**, looks up the child views once and keeps the references as fields. RecyclerView calls it only when it needs a holder of that type and has none it can reuse. - **`onBindViewHolder(holder, position)`** writes one item's data into a holder that already exists. It runs every time a holder is shown for an item, and the holder may have displayed a completely different item a moment ago. A `ViewHolder` is the row's `itemView` plus the cached references to its children. Caching them in the holder is what the javadoc recommends so that a bind never repeats `findViewById` work. ## What "recycling" actually reuses When a row scrolls off screen, RecyclerView does not destroy its view. It keeps a small **offscreen view cache** (two views by default, `setItemViewCacheSize` changes it) that can be reattached to the same position without a rebind. Beyond that, holders go to the **`RecycledViewPool`**, grouped by view type (five per type by default). A holder taken from the pool **must be rebound**, because it still carries whatever the previous item set on it. That is why the rule for `onBindViewHolder` is simple: **set every view property that any item could change, on every bind, in both branches of every condition.** | Code in `onBindViewHolder` | What happens on a recycled holder | |---|---| | `if (book.isDownloaded) badge.visibility = View.VISIBLE` | the badge stays visible for the next, not-downloaded book | | `badge.visibility = if (book.isDownloaded) View.VISIBLE else View.GONE` | correct for every item | | starts an image load and never clears the old image | the previous cover flashes until the new one arrives | In an audiobook library, the symptom is a "downloaded" tick or a stale progress bar showing on a book the user never downloaded, usually only after scrolling, which is why it slips past a quick manual test. ## Positions are not stable inside a holder The javadoc is explicit: RecyclerView **will not call `onBindViewHolder` again just because an item's position changed** (for example when a row above it is inserted), unless the item itself is invalidated or its new position cannot be determined. So: 1. Use the `position` argument only to fetch the item during the bind. 2. Never capture it in a click listener. 3. In a listener, ask the holder at click time with `getBindingAdapterPosition()` and check it against `RecyclerView.NO_POSITION`, which it returns while the holder is not bound to an item (for example during a removal). `getAdapterPosition()` was deprecated in RecyclerView 1.2.0, when `ConcatAdapter` arrived, and replaced by two methods: `getBindingAdapterPosition()` (the position inside the adapter that bound the holder) and `getAbsoluteAdapterPosition()` (the position in the whole RecyclerView). ## Where each kind of work belongs - **In `onCreateViewHolder`:** inflation, child lookups, listeners that read the position at click time, and anything that is the same for every item of that type. - **In `onBindViewHolder`:** text, images, visibility, enabled and checked state, content descriptions: everything that depends on the item. - **In `onViewRecycled(holder)`:** releasing heavy resources bound to the row, such as a large bitmap or an image request. RecyclerView calls it right before clearing the holder and sending it to the pool. Inflate with `attachToRoot = false`. `createViewHolder` checks this and throws an `IllegalStateException` whose message says ViewHolder views must not be attached when created. ## How to spot the bug in review - Look for an `if` without an `else` in a bind that touches visibility, colour, checked state or alpha. - Look for `position` used inside a lambda created in the bind. - Look for per-item state (a checked box, an expanded section) kept only in the view; it disappears or moves when the holder is reused, so keep it in the item data and bind it back. Compose lazy lists and the platform-neutral design of virtualised lists are separate lessons; the point here is how RecyclerView's own two callbacks split the work.

  • Does a holder reattached from RecyclerView's offscreen view cache go through onBindViewHolder again?
    Not necessarily. The offscreen view cache, two views by default and sized with `setItemViewCacheSize`, keeps holders that can be reattached to the same position unmodified, without returning to the adapter. Holders that spill into the `RecycledViewPool` are different: they must be rebound before reuse. That is why a fling back and forth over a few rows may not hit your bind at all.
  • Where should a RecyclerView adapter release a large bitmap or cancel an image request for a row?
    In `onViewRecycled(holder)`. RecyclerView calls it right before clearing the holder's internal data and sending it to the `RecycledViewPool`, and the javadoc names large bitmaps as the case it is for. The next bind then starts from a clean row instead of flashing the old cover.
  • Why does inflating a RecyclerView row with attachToRoot set to true crash?
    `createViewHolder` checks that the new holder's `itemView` has no parent and throws an `IllegalStateException` saying ViewHolder views must not be attached when created. RecyclerView attaches and detaches rows itself, so `onCreateViewHolder` must inflate with `inflate(layout, parent, false)`.

  • onCreateViewHolder runs once for every item in the adapter's list
  • Only setting a view when a condition is true is enough because new rows start clean
  • Capturing the bind's position in a click listener is safe because RecyclerView rebinds on every move
  • getAdapterPosition is the current way to read a holder's position inside a ConcatAdapter
  • Per-row state such as an expanded section can live only in the view