In RecyclerView, how do getItemViewType and GridLayoutManager's SpanSizeLookup together make section headers span a tablet grid's full width?
answer
- two jobs, two classes
- type picks the holder
- lookup picks the column count
- span size never above spanCount
- full span on the staggered grid's LayoutParams
basics
~10 sgetItemViewType tells the adapter which layout and ViewHolder each position uses, so headers and books get different holders. GridLayoutManager's SpanSizeLookup then returns the full span count for header positions and one span for books.
solid answer
~30 sThe adapter overrides `getItemViewType(position)` to return a distinct int per row kind, often the layout id; `onCreateViewHolder` inflates the matching layout, and the `RecycledViewPool` keeps holders per type so a header holder is never reused for a book. The grid is the LayoutManager's job: `GridLayoutManager(context, spanCount)` plus a `SpanSizeLookup` whose `getSpanSize(position)` returns `spanCount` for headers and 1 for books. Returning more than the span count throws an `IllegalArgumentException`. On a `StaggeredGridLayoutManager` the equivalent is `setFullSpan(true)` on the header's layout params, and grid gutters belong in an `ItemDecoration`, not in bind-time margins.
code
kotlin · 19 linessealed interface LibraryRow {
data class Header(val genre: String) : LibraryRow
data class BookRow(val book: Book) : LibraryRow
}
override fun getItemViewType(position: Int): Int = when (getItem(position)) {
is LibraryRow.Header -> R.layout.item_section_header
is LibraryRow.BookRow -> R.layout.item_book
}
// In the Fragment
val spanCount = resources.getInteger(R.integer.library_columns)
val grid = GridLayoutManager(requireContext(), spanCount)
grid.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int =
if (adapter.getItemViewType(position) == R.layout.item_section_header) spanCount else 1
}
recyclerView.layoutManager = grid
recyclerView.adapter = adaptergo deeper
Recall that getItemViewType picks the row layout and that GridLayoutManager places rows in a number of spans.
Walk through view type to onCreateViewHolder to per-type pooling, and write a SpanSizeLookup that gives headers the whole span count.
Handle span count changes on rotation, the IllegalArgumentException for oversized spans, ConcatAdapter positions in a lookup, and gutters in an ItemDecoration.
Keep phone and tablet on one adapter and one set of view types, varying only the LayoutManager and its span count from resources.
## The scenario An audiobook library shows section headers ("Mystery", "Science fiction") between book rows. On phones it is a single column; on tablets the books sit in a grid while each header still runs the full width. RecyclerView solves this with two separate mechanisms that are easy to confuse: - **`getItemViewType(position)`** on the adapter decides **which layout and ViewHolder** a position uses. - **`GridLayoutManager.SpanSizeLookup`** on the LayoutManager decides **how many columns** a position occupies. ## View types: one adapter, several row layouts `getItemViewType` returns 0 by default, meaning one type. Override it to return a different integer per kind of row. RecyclerView passes that integer to `onCreateViewHolder(parent, viewType)`, so you can inflate the right layout and build the right holder class. The javadoc adds two details worth knowing: - Type codes **need not be contiguous**, unlike the older list widget's adapters. - It suggests using **id resources** so types are unique; returning the row's layout id (`R.layout.item_section_header`) is a common pattern. View types also partition recycling. The `RecycledViewPool` keeps holders **per type**, so a header holder is never handed to a book row. That is exactly what you want, and it is also why every type needs its own `onCreateViewHolder` branch and a bind that casts to the right holder. Typical model shape in Kotlin: 1. A sealed class or interface for rows, such as `LibraryRow.Header` and `LibraryRow.BookRow`. 2. `getItemViewType` maps each subclass to a type with an exhaustive `when`. 3. `onCreateViewHolder` maps the type back to a layout and holder. 4. `onBindViewHolder` binds by holder type. ## Span sizes: the grid's job `GridLayoutManager(context, spanCount)` lays rows out in `spanCount` columns for a vertical list. By default each item takes one span (`DefaultSpanSizeLookup`). A header must take all of them: ```kotlin grid.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int) = if (adapter.getItemViewType(position) == R.layout.item_section_header) grid.spanCount else 1 } ``` Rules that come straight from the source: - `getSpanSize` receives an **adapter position** and returns the number of spans. - Returning more than the span count throws an `IllegalArgumentException` saying the item at that position requires more spans than the GridLayoutManager has. - `setSpanCount` rejects values below 1 and invalidates the span index cache; call it when a tablet rotates and the column count changes. - If `getSpanIndex` is costly, `setSpanIndexCacheEnabled(true)` caches results; caching is off by default. ## Choosing the LayoutManager | LayoutManager | Use it when | Full-width header | |---|---|---| | `LinearLayoutManager` | one column or a horizontal row | every item is already full width | | `GridLayoutManager` | equal-height cells in a grid | `SpanSizeLookup` returns the span count | | `StaggeredGridLayoutManager` | cells of different heights, like covers of mixed aspect ratios | `StaggeredGridLayoutManager.LayoutParams.setFullSpan(true)` on the header's layout params | Switching from phone to tablet is a LayoutManager change, not an adapter change: the same adapter and view types serve both, and only the span count and lookup differ. Many apps read the column count from a resource that varies by smallest width. ## Spacing belongs in an ItemDecoration A grid needs gutters, and the tempting fix is margins in `onBindViewHolder`. That couples layout to binding and breaks when spans change. RecyclerView's tool is an **`ItemDecoration`**: - `getItemOffsets(outRect, view, parent, state)` adds insets around each child, which the LayoutManager respects when measuring. - `onDraw` draws beneath children and `onDrawOver` draws above them, such as dividers or a sticky header drawn over the list. - `DividerItemDecoration` covers the plain divider case for linear lists. Inside `getItemOffsets`, read the child's position with `parent.getChildAdapterPosition(view)` and its span index from `GridLayoutManager.LayoutParams` to give edge columns the right inset. ## When the adapter is a ConcatAdapter If headers come from a separate adapter joined with `ConcatAdapter`, the lookup sees global positions. Since RecyclerView 1.3.0, `ConcatAdapter.getWrappedAdapterAndPosition(globalPosition)` returns the wrapped adapter and its local position, which the release notes name as the tool for a `SpanSizeLookup`.
- How do you add even gutters between cells of a RecyclerView grid?Add an `ItemDecoration` and override `getItemOffsets(outRect, view, parent, state)`, using the child's span index from `GridLayoutManager.LayoutParams` to size edge insets. The LayoutManager accounts for those offsets when it measures children. Margins set in `onBindViewHolder` couple layout to binding and go wrong when the span count changes.
- The tablet rotates and the RecyclerView grid should go from three to four columns. What do you call?`GridLayoutManager.setSpanCount(4)`, or build a new GridLayoutManager when the view is recreated. `setSpanCount` rejects values below 1, invalidates the span index cache and requests a layout. A lookup that returns the span count for headers must read the current value, not a constant captured earlier.
- Can two different RecyclerView row kinds share one view type?Only if they use the same layout and ViewHolder class, because the `RecycledViewPool` hands any holder of that type to any position of that type. If the layouts differ, give them different types; otherwise a bind receives a holder built for the other layout.
- View types must be numbered 0, 1, 2 without gaps
- SpanSizeLookup decides which layout a header row inflates
- A span size larger than spanCount is silently clamped to the full width
- Grid spacing should be set with margins inside onBindViewHolder
- StaggeredGridLayoutManager headers use a SpanSizeLookup too