Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 104 ยท Legacy Views

RecyclerView: Adapters, ViewHolders and DiffUtil

Learn RecyclerView on Android: ViewHolder, Adapter, ListAdapter with DiffUtil, layout managers, click handling, multiple view types, ItemDecoration and swipe, versus LazyColumn.

Before Compose, every scrolling list on Android was a RecyclerView. Millions of apps still use it, so you will read it, fix it and migrate it. The idea is simple: a list of 10,000 rows never needs 10,000 views. The screen shows about ten rows at a time, so RecyclerView creates roughly a dozen row views and recycles them: when a row scrolls out of sight, the same view object is reused for the next row that scrolls in, with new data poured into it.

That reuse is what makes the API look heavy. Three roles cooperate: an Adapter that knows your data, a ViewHolder that remembers the views inside one row, and a LayoutManager that decides where rows go. This lesson explains each role, then ListAdapter with DiffUtil (the modern default), multiple row types, click handling, decorations, swipe-to-delete and how it all compares with LazyColumn. The Android classes cannot run on this site, so the real code is read-only; the TryIts are plain-Kotlin stand-ins that model view recycling and the diff algorithm idea, and they say what is real and what is simplified.

The three roles

flowchart LR
    D["Your data<br/>List of Task"] --> A["Adapter<br/>creates and binds"]
    A --> H["ViewHolder<br/>row views, reused"]
    L["LayoutManager<br/>positions rows"] --> RV["RecyclerView"]
    H --> RV

The Adapter turns data into row views, the LayoutManager arranges them, RecyclerView scrolls and recycles.

  • A ViewHolder wraps one row's root view and caches the child views (or the view binding), so you do not call findViewById on every bind.
  • An Adapter answers three questions: how many items (getItemCount), how to make an empty row (onCreateViewHolder) and how to fill a row with item n (onBindViewHolder).
  • A LayoutManager measures and places rows: LinearLayoutManager (vertical or horizontal list), GridLayoutManager (columns) and StaggeredGridLayoutManager (uneven heights).

Here is the classic minimal adapter with View Binding. The XML for the row and the screen is shown in XML Layouts.

Kotlin
// read-only example: a basic adapter
class TaskAdapter(private val tasks: List<Task>) :
    RecyclerView.Adapter<TaskAdapter.TaskViewHolder>() {

    class TaskViewHolder(val binding: ItemTaskBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return TaskViewHolder(ItemTaskBinding.inflate(inflater, parent, false))
    }

    override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
        val task = tasks[position]
        holder.binding.title.text = task.title
        holder.binding.done.isChecked = task.done
    }

    override fun getItemCount(): Int = tasks.size
}

// in the Activity or Fragment
binding.list.layoutManager = LinearLayoutManager(this)
binding.list.adapter = TaskAdapter(tasks)

The key rule is that onBindViewHolder runs for recycled views. The view you receive may still show the previous row's text, a checked box or a hidden progress bar. Always set every property that can vary, including the "else" case. Forgetting to reset a checkbox is the classic bug where scrolling makes ticks jump to the wrong rows.

The first stand-in models exactly this. A pool of holder objects is created once; as you "scroll", holders are rebound to new positions. It counts how many holders were created versus how many binds happened, and it also shows the stale-state bug.

Kotlin View recycling: few holders, many binds (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

With 1,000 rows only eight holders are ever created. (The real widget keeps a few extra off-screen holders in its cache, so expect a handful more.) The buggy variant shows why every branch of onBindViewHolder must assign. Real RecyclerView has a more elaborate cache (a scrap list, a "cached views" tier and a shared RecycledViewPool), but the principle is the one in the stand-in.

ListAdapter and DiffUtil

Calling notifyDataSetChanged() after every change redraws everything and kills animations. The better tool is ListAdapter, which extends RecyclerView.Adapter, keeps its own list and, on submitList(newList), compares the old and new lists on a background thread with DiffUtil, then dispatches precise insert, remove, move and change events, so rows animate smoothly.

You teach it two things in a DiffUtil.ItemCallback:

  • areItemsTheSame: do these two objects represent the same thing? Compare stable IDs.
  • areContentsTheSame: if so, did anything visible change? For a data class, == is enough.
Kotlin
// read-only example: ListAdapter with DiffUtil and a click callback
class TaskAdapter(private val onClick: (Task) -> Unit) :
    ListAdapter<Task, TaskAdapter.VH>(Diff) {

    object Diff : DiffUtil.ItemCallback<Task>() {
        override fun areItemsTheSame(old: Task, new: Task) = old.id == new.id
        override fun areContentsTheSame(old: Task, new: Task) = old == new
    }

    inner class VH(private val binding: ItemTaskBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(task: Task) {
            binding.title.text = task.title
            binding.done.isChecked = task.done
            binding.root.setOnClickListener { onClick(task) }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        VH(ItemTaskBinding.inflate(LayoutInflater.from(parent.context), parent, false))

    override fun onBindViewHolder(holder: VH, position: Int) = holder.bind(getItem(position))
}

// observe state and hand the adapter a NEW list instance
viewModel.tasks.observe(viewLifecycleOwner) { adapter.submitList(it) }

Two details trip people up. First, submitList ignores a list that is the same instance as the current one, so if you mutate a MutableList in place and resubmit it, nothing updates: always pass a new list (list + item, list.toList()). Second, areItemsTheSame must use identity, not equality; if it used ==, an edited item would look like a removed row plus an added row and lose its animation.

The second stand-in implements a small diff on item IDs to show what events the adapter would dispatch, which is the output that drives the animations. The real DiffUtil uses Myers' algorithm and also detects moves; this stand-in only reports inserts, removals and changes.

Kotlin What DiffUtil decides: inserts, removes, changes (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Multiple view types

Chat screens and feeds mix rows: a date header, a received message, a sent message. Override getItemViewType(position) to return a number per kind, and branch in onCreateViewHolder. Each type gets its own holder class and its own recycling pool.

Kotlin
// read-only example: two row types
sealed interface Row {
    data class Header(val label: String) : Row
    data class Message(val id: Long, val text: String, val mine: Boolean) : Row
}

override fun getItemViewType(position: Int) = when (getItem(position)) {
    is Row.Header -> TYPE_HEADER
    is Row.Message -> TYPE_MESSAGE
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
    when (viewType) {
        TYPE_HEADER -> HeaderVH(ItemHeaderBinding.inflate(inflater(parent), parent, false))
        else -> MessageVH(ItemMessageBinding.inflate(inflater(parent), parent, false))
    }

A Kotlin sealed interface for the row model keeps the when exhaustive. Compare it with a LazyColumn, where you simply write items(rows) { row -> when (row) { ... } } and the "view type" is a contentType hint.

Layout managers, horizontal and nested lists

Switching the layout is a one-line change:

Kotlin
// read-only example
binding.list.layoutManager = GridLayoutManager(context, 2)                       // two columns
binding.chips.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
binding.photos.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)

A GridLayoutManager.SpanSizeLookup lets a header span all columns. For a vertical list with a horizontal carousel inside each row (the "shelves" layout), give each inner RecyclerView its own adapter, and share one RecycledViewPool between them so inner row views are reused across shelves. Set setHasFixedSize(true) when the list size does not change the list's own bounds, which saves layout passes. Never put a RecyclerView inside a ScrollView and let it expand to full height: it measures and binds every item and loses recycling.

Click handling

Do not set click listeners in onBindViewHolder with the adapter position captured, because the position can be stale after inserts. Two safe styles:

  1. Set the listener in the ViewHolder and use getItem(bindingAdapterPosition) at click time (checking for NO_POSITION).
  2. Capture the item (not the index) in bind, as the ListAdapter example does with onClick(task).

Pass behavior in as lambdas, as above, so the adapter stays free of navigation and ViewModel code.

Decorations, animations and swipe

  • ItemDecoration draws dividers and spacing around rows without touching row layouts. DividerItemDecoration is built in; for spacing, override getItemOffsets.
  • ItemAnimator animates insertions and removals. DefaultItemAnimator is on by default and works well with ListAdapter.
  • ItemTouchHelper adds swipe-to-dismiss and drag-to-reorder:
Kotlin
// read-only example: swipe to delete
val callback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
    override fun onMove(rv: RecyclerView, vh: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder) = false
    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
        viewModel.delete(adapter.currentList[viewHolder.bindingAdapterPosition])
    }
}
ItemTouchHelper(callback).attachToRecyclerView(binding.list)

Note that the swipe handler asks the ViewModel to change the data; the list updates when new data arrives through submitList. Do not remove the row from the adapter yourself and leave the model unchanged, or the two will disagree.

Other useful pieces are ConcatAdapter (joins adapters, such as a header adapter and a content adapter), PagingDataAdapter for Paging and SnapHelper for carousels.

RecyclerView versus LazyColumn

Topic RecyclerView LazyColumn
Row definition XML layout, ViewHolder, Adapter A composable lambda
Change detection DiffUtil callbacks key and compose equality
Recycling Views are reused and rebound Composition slots are reused; no view objects
Row types getItemViewType contentType
Boilerplate High Low
Mature extras ItemTouchHelper, ConcatAdapter, many third-party libraries Built from modifiers and state

New screens should use Compose. Keep RecyclerView when you maintain an XML screen; you can host a LazyColumn through ComposeView or, in the other direction, a RecyclerView through AndroidView, as shown in Compose and Views Interop.

Common mistakes

  • Not resetting every property in onBindViewHolder. Recycled rows show stale checkmarks and images.
  • Using notifyDataSetChanged() for everything. Prefer ListAdapter and submitList.
  • Mutating the list passed to submitList. Pass a new list instance.
  • Comparing contents in areItemsTheSame. Compare stable IDs there; use equality in areContentsTheSame.
  • Using the position captured at bind time in a click listener. Use the item or bindingAdapterPosition.
  • Doing heavy work in onBindViewHolder. It runs while scrolling; precompute in the ViewModel.
  • Nesting a RecyclerView in a ScrollView. It loses recycling and becomes slow.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does RecyclerView do when a row scrolls out of view?

    Recycling reuses a small set of view objects. That is why onBindViewHolder must overwrite every property that can differ between rows.
  2. 2. You mutate the MutableList you gave to a ListAdapter and call submitList with the same list. What happens?

    ListAdapter skips a submit when the list instance is the same as the current one. Always submit a new list.
  3. 3. In DiffUtil.ItemCallback, what should areItemsTheSame compare?

    Identity says whether two objects are the same row; areContentsTheSame then decides whether it needs to be redrawn.
  4. 4. Which API adds swipe-to-dismiss to a RecyclerView?

    ItemTouchHelper handles swipe and drag gestures; the callback should ask the ViewModel to change the data.
  5. 5. Which Compose feature plays the role of getItemViewType?

    contentType tells a lazy list which items can share composition work, similar to view types in a RecyclerView.

Summary

  • RecyclerView reuses a few row views and rebinds them; an Adapter supplies data, a ViewHolder caches row views and a LayoutManager places them.
  • onBindViewHolder must set every varying property, because it receives recycled views.
  • ListAdapter with DiffUtil animates precise changes; submit a new list and compare identity in areItemsTheSame.
  • Use getItemViewType for mixed rows, and layout managers for lists, grids and carousels.
  • Click handlers should use the item or bindingAdapterPosition, and pass behavior as lambdas.
  • ItemDecoration, ItemAnimator and ItemTouchHelper add dividers, animation and swipe.
  • In new code, LazyColumn does the same job with far less boilerplate.
  • The TryIts are plain-Kotlin stand-ins for recycling and diffing; the Android code is read-only.

Next: Fragments and the Fragment Lifecycle