RecyclerView Multiple View Types: A Practical Kotlin Guide
A chat screen, a settings page, or a product feed rarely uses one row layout. You have headers, messages, images, and ads mixed together. RecyclerView handles this through `getItemViewType()`, but the implementation details decide whether scrolling stays smooth or starts to jank.
This guide walks through a clean Kotlin implementation: a sealed model, a view type map, correct `onCreateViewHolder` and `onBindViewHolder` overrides, and DiffUtil with payloads. You will also see which mistakes cause the most common bugs and how to measure the result.
Model your rows before you touch the adapter
The fastest way to create bugs in a multi-type adapter is to shove everything into one data class with nullable fields. Instead, define a sealed interface or sealed class that represents each row kind. Kotlin's exhaustive `when` then forces you to handle every type in both creation and binding, which eliminates the classic `ClassCastException` when a header is bound to a message view holder.
Keep the model free of Android types. A `Header`, `TextMessage`, and `ImageMessage` data class can live in your domain layer and be unit tested without a device. If you use Room or an API response, map to this model once at the boundary. The adapter then only knows about the sealed type, not where the data came from.
- Use a sealed interface with a stable `id` property for DiffUtil
- Avoid nullable fields that only apply to one row type
- Map network or database models to UI models at the repository boundary
Map item types to constants, not positions
`getItemViewType(position)` must return a value that depends only on the item, never on its position. A common bug is returning different types for the same object when it moves, which confuses RecyclerView's view recycling and causes duplicated or missing rows. Derive the type from the sealed class instance itself.
Constants should be stable integers. Use a `when` expression to map each sealed subtype to a distinct constant. If you later add a new row type, the compiler will flag missing branches. Keep the constants in the adapter's companion object, or better, in a private object so no other class can accidentally depend on them.
Create view holders with correct layout params
`onCreateViewHolder` receives the view type and must inflate the matching layout. Always pass the parent and `false` to the inflater: `LayoutInflater.from(parent.context).inflate(R.layout.item_header, parent, false)`. Passing `null` as the parent removes the layout params that RecyclerView relies on, and you get rows that ignore margins or match-parent widths.
If you use View Binding, generate the binding class with the same inflater call. Keep one view holder class per row type, or a generic holder that accepts a binding. The latter reduces boilerplate but can hide type errors, so many teams prefer explicit holders for clarity. Either way, do not cache bindings in the adapter; the holder owns them.
Bind with payloads to avoid full rebinds
`onBindViewHolder` is called every time a row scrolls into view, so keep it cheap. Set text, load images through your image loader, and avoid creating new listeners inside bind. For changing content, use the payload version of `onBindViewHolder` and send a payload from DiffUtil. A message that only changed its read status does not need its avatar reloaded.
Payloads are plain objects. Define a small sealed class or enum for update kinds, such as `ReadStatusChanged`. In the payload override, handle only the affected views and fall back to the full bind when the payload list is empty. This is the single biggest win for lists that update frequently, such as chat or live scores.
- Never create lambdas inside `onBindViewHolder`; create them once in the holder
- Use `ListAdapter` or `AsyncListDiffer` for background diffing
- Send payloads for partial updates
| Mistake | Symptom | Typical fix | Effort |
|---|---|---|---|
| Type depends on position | Duplicate or missing rows after scroll | Derive type from sealed model | Low |
| Inflate with null parent | Margins and widths ignored | Pass parent and false | Low |
| New listeners in onBind | Allocation churn, jank | Create listeners in holder init | Low |
| No stable IDs | Flicker on insert or move | Override getItemId and enable | Medium |
| Full rebind for small change | Dropped frames on updates | DiffUtil payloads | Medium |
| Nested RecyclerView with wrap_content | Slow measure pass | Fixed height or setHasFixedSize | Medium |
Measure scrolling and fix the usual suspects
On mid-range devices, a list with mixed image and text rows should hold 60 fps during a fling. If you see dropped frames, check for `onBindViewHolder` work that exceeds roughly 1–2 ms per row, image decoding on the main thread, or nested `wrap_content` RecyclerViews. Android Studio's Profiler and `adb shell dumpsys gfxinfo` give you frame timing without guesswork.
Stable IDs help animations and reduce flicker when items move. Override `getItemId()` using the model's unique id and call `setHasStableIds(true)` in the adapter constructor. Combined with DiffUtil, this keeps item animations correct when you insert a header or reorder messages. If you also use data binding, the same identity rules apply; see Data Binding in RecyclerView: Setup and Common Pitfalls for the binding-specific traps.
Keep the adapter testable and the layout simple
Put the type mapping in a pure function so you can unit test it without Robolectric. The adapter becomes a thin shell that delegates to view holders. This structure also makes it easy to swap the list for a `ListAdapter` subclass when you add DiffUtil later. Small, focused classes age better than a 400-line adapter.
For layout, avoid deep hierarchies inside each row. A `ConstraintLayout` with a handful of views outperforms nested `LinearLayout`s, especially when rows contain images. If you are deciding between row styles for iOS and Android, Cupertino vs Material Widgets: Which Style Fits Your App? covers the trade-offs without changing the adapter structure.
Key points
- Model rows as a sealed type so Kotlin enforces exhaustive handling.
- Return view types from the item, never from its position.
- Inflate with the parent attached and false to keep layout params.
- Use stable IDs and DiffUtil payloads for smooth updates.
Flutter Screen Widget and Cost Estimator
Estimate the number of widgets in a screen and a rough development-hour figure from your component counts. Adjust the fields to see how each UI area affects the total effort.
Editor and Flutter contributor
Writes practical Flutter tutorials focused on widgets, layout and animation. Enjoys breaking large UI problems into small, testable pieces and explaining them clearly to beginners.