skip to content

In a vertical RecyclerView with horizontal carousels nested in its rows, how do a shared RecycledViewPool and setInitialPrefetchItemCount stop the scroll hitch?

level: seniorimportance: should knowfreq 40%

answer

  1. every RecyclerView owns a pool
  2. carousels can share one
  3. same view types across adapters
  4. inner prefetch defaults to two
  5. five holders per type by default

basics

~20 s

Each nested RecyclerView otherwise has its own empty pool and inflates cards when its row appears. Sharing one RecycledViewPool lets carousels reuse card holders, and setInitialPrefetchItemCount makes prefetch build the visible cards before the row scrolls in.

solid answer

~30 s

A RecyclerView creates its own `RecycledViewPool` unless given one, so every newly bound carousel row starts empty and inflates each card inside the frame it appears in. Create one pool and call `setRecycledViewPool` on every inner RecyclerView; adapters sharing it must use the same view types and holder classes, and `setMaxRecycledViews` raises the default of five holders per type. Prefetch can create and bind inner items before the row is on screen, but `LinearLayoutManager` prefetches only two by default; `setInitialPrefetchItemCount(4)` for a four-card carousel moves that work out of the visible frame. `setRecycleChildrenOnDetach(true)` returns cards to the shared pool sooner.

code

kotlin · 24 lines
kotlin
class ShelfViewHolder(
    itemView: View,
    sharedPool: RecyclerView.RecycledViewPool,
) : RecyclerView.ViewHolder(itemView) {
    val carousel: RecyclerView = itemView.findViewById(R.id.carousel)
    val cardsAdapter = CoverCardAdapter()

    init {
        carousel.layoutManager = LinearLayoutManager(
            itemView.context, LinearLayoutManager.HORIZONTAL, false
        ).apply {
            initialPrefetchItemCount = 4
            recycleChildrenOnDetach = true
        }
        carousel.setRecycledViewPool(sharedPool)
        carousel.adapter = cardsAdapter
    }
}

// In the outer adapter: one pool for every carousel row
private val cardPool = RecyclerView.RecycledViewPool().apply {
    // CoverCardAdapter returns R.layout.item_cover_card as its view type
    setMaxRecycledViews(R.layout.item_cover_card, 12)
}

go deeper

for a junior

Know that each RecyclerView keeps its own pool of recycled rows unless you give it a shared one.

for a middle

Explain how setRecycledViewPool and per-type pooling let carousels reuse card holders, and what initial prefetch does for a nested list.

for a senior

Diagnose a nested-list hitch, set pool sizes and the initial prefetch count from what each carousel shows, and restore each carousel's scroll offset.

for a principal

Weigh memory held by pooled and prefetched views against smoothness, and keep view types consistent across adapters that share a pool.

## The scenario The audiobook library's vertical list includes a horizontal **"Continue listening"** carousel, and a tablet layout adds a horizontal shelf per genre. Each carousel is a `RecyclerView` inside a row of the outer `RecyclerView`. Users report a hitch every time a carousel scrolls into view, and a heap dump shows far more cover-card views than are ever on screen. Two RecyclerView features target exactly this: a **shared `RecycledViewPool`** and **initial prefetch** for nested lists. ## Why nested lists jank by default - **Every RecyclerView creates its own pool** if you do not give it one. When a carousel row is recycled and a different carousel row is bound, the new inner RecyclerView starts with an empty pool and must call `onCreateViewHolder` (inflate) for every card it shows. - **Prefetch only sees the outer list.** While the UI thread is idle between frames (API 21 and higher), RecyclerView's prefetch creates and binds rows about to scroll in. For a nested RecyclerView, the outer prefetch can also ask the inner LayoutManager for its first items, but `LinearLayoutManager` defaults to **2** initial prefetch items. A carousel that shows four cards does the other two inside the frame in which it appears. ## Fix 1: one RecycledViewPool for all carousels The javadoc says recycled view pools let **multiple RecyclerViews share a common pool** when their adapters use the same view types. Create one pool in the outer adapter (or the Fragment), and in each carousel holder call `carousel.setRecycledViewPool(sharedPool)`. Details that matter: 1. **View types must mean the same thing across the sharing adapters.** The pool is keyed by view type only; a card holder created by one carousel adapter will be bound by another, so they must use the same holder class for that type. 2. **Size the pool.** The default keeps **5 holders per view type**. If two carousels with six visible cards each can be off screen at once, raise it with `setMaxRecycledViews(viewType, max)`. 3. **Return cards to the pool promptly.** `LinearLayoutManager.setRecycleChildrenOnDetach(true)` recycles a carousel's children when its RecyclerView is detached; its javadoc suggests this when using a shared pool so views are available to other RecyclerViews immediately, and warns it costs performance if that RecyclerView is restored. 4. **Set the pool once**, in the holder's creation, not on every bind. ## Fix 2: initial prefetch for the inner LayoutManager `LinearLayoutManager.setInitialPrefetchItemCount(n)` tells RecyclerView how many inner items to prefetch when the nested RecyclerView is about to scroll into the viewport. The javadoc's own example is a vertical list of horizontal rows showing four items each, where passing 4 lets prefetch create and bind four views early instead of the default 2. | Setting | Default | What it does | Cost if too high | |---|---|---|---| | `setInitialPrefetchItemCount` | 2 | create and bind the first inner items before the row appears | extra binds and views for cards never shown | | `setMaxRecycledViews` | 5 per type | how many idle holders the pool keeps | memory held by idle views | | `setItemPrefetchEnabled` | true | prefetch between frames at all | turning it off brings back the hitch | | `setItemViewCacheSize` | 2 | offscreen views reusable without rebind | memory, and fewer holders reach the pool | The javadoc states that initial prefetch does nothing unless the LayoutManager's RecyclerView is nested inside another RecyclerView. ## Keeping each carousel's scroll offset Recycling the outer row also recycles the inner RecyclerView, so a user who scrolled "Continue listening" to the fifth card can come back to a different offset: the holder that returns may last have shown another shelf, or none. The LayoutManager can save and restore its own state: store `layoutManager.onSaveInstanceState()` keyed by the row's id in `onViewRecycled`, and pass it to `onRestoreInstanceState` when binding that row again. Where row state should live in general is a design question covered with list virtualisation; here it is just these two LayoutManager calls. ## Order of operations in the carousel holder 1. In `onCreateViewHolder`: inflate the row, build the horizontal `LinearLayoutManager`, set its initial prefetch count, set the shared pool, create the inner adapter. 2. In `onBindViewHolder`: `submitList` the row's books to the inner `ListAdapter` and restore the saved scroll state. 3. In `onViewRecycled`: save the scroll state.

  • What breaks if two RecyclerView adapters share a RecycledViewPool but use the same view type for different layouts?
    The pool is keyed only by view type, so a holder created by one adapter can be handed to the other, whose bind then receives a holder built for a different layout or class. Sharing a pool requires that a given view type means the same layout and holder class in every adapter using it.
  • Why does a carousel inside a RecyclerView row lose its horizontal scroll position after scrolling away and back?
    The outer row was recycled, and the holder that binds it again may last have shown another shelf, so the inner LayoutManager's offset is not this row's. Save `layoutManager.onSaveInstanceState()` keyed by the row's id in `onViewRecycled`, and call `onRestoreInstanceState` with it when that row is bound again.
  • Does setInitialPrefetchItemCount do anything on a top-level RecyclerView?
    No. The javadoc says calling it does nothing unless the LayoutManager's RecyclerView is nested inside another RecyclerView. Top-level prefetch is controlled by `setItemPrefetchEnabled`, which is on by default.

  • Nested RecyclerViews share one RecycledViewPool automatically
  • A shared pool works across adapters whatever view types they return
  • setInitialPrefetchItemCount speeds up a top-level RecyclerView too
  • Setting the shared pool in onBindViewHolder each time is required
  • A bigger initial prefetch count is always better