Views, layouts and RecyclerView
A View-based screen has two halves: an XML layout that describes the tree of views, and Kotlin code that finds those views and fills them with data.
- ConstraintLayout positions views relative to each other and to the parent (“below the title, 16dp from the start”), which keeps the tree flat.
LinearLayoutstacks children in a row or column. - ViewBinding generates a class per layout with a typed property for each view that has an id:
binding.title.text = recipe.name. It replacedfindViewByIdand the old Kotlin synthetics, which were removed in Kotlin 1.8.
Long lists use RecyclerView. Instead of creating a view for each of 1,000 rows, it creates only enough ViewHolders to fill the screen and a few extra, and recycles them: when a row scrolls off the top, its ViewHolder is reused for the row appearing at the bottom, and onBindViewHolder fills it with the new row’s data.
That reuse is the source of the most common RecyclerView bug: a recycled ViewHolder still shows whatever the previous row left in it, unless you set every property in onBindViewHolder.
Rendering runs in three passes over the tree: measure (each parent asks children how big they want to be under MeasureSpec constraints: EXACTLY, AT_MOST, UNSPECIFIED), layout (parents position children) and draw. invalidate() schedules only a redraw; requestLayout() re-runs measure and layout up the tree, which is far more expensive, and calling it on every frame or every bind causes jank. Nested LinearLayout weights and RelativeLayout measure children twice per level, so deep nesting multiplies measure passes; ConstraintLayout keeps trees flat. Custom views override onMeasure (call setMeasuredDimension), onLayout for groups and onDraw (allocate no objects there). RecyclerView: a LayoutManager places items, ViewHolders are pooled per view type in a RecycledViewPool (shareable between nested lists), and ListAdapter diffs submitted lists with DiffUtil on a background thread (AsyncListDiffer), producing item-level animations instead of notifyDataSetChanged()’s full rebind; DiffUtil.ItemCallback needs a stable identity in areItemsTheSame and a content check in areContentsTheSame, and getChangePayload enables partial rebinds. setHasFixedSize(true) avoids re-measuring the RecyclerView when only content changes. View state survives configuration changes through onSaveInstanceState only for views with an id.
class RecipeAdapter(
private val onFavorite: (Recipe, Boolean) -> Unit,
) : ListAdapter<Recipe, RecipeAdapter.Holder>(Diff) {
class Holder(val binding: ItemRecipeBinding) : RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
Holder(ItemRecipeBinding.inflate(LayoutInflater.from(parent.context), parent, false))
override fun onBindViewHolder(holder: Holder, position: Int) {
val recipe = getItem(position)
holder.binding.title.text = recipe.name
holder.binding.favorite.setOnCheckedChangeListener(null) // don't fire for the old row
holder.binding.favorite.isChecked = recipe.isFavorite // set every property, every time
holder.binding.favorite.setOnCheckedChangeListener { _, checked -> onFavorite(recipe, checked) }
}
object Diff : DiffUtil.ItemCallback<Recipe>() {
override fun areItemsTheSame(old: Recipe, new: Recipe) = old.id == new.id
override fun areContentsTheSame(old: Recipe, new: Recipe) = old == new
}
}
// In the screen: adapter.submitList(recipes) // diffs on a background thread and animates the changes<!-- res/layout/item_recipe.xml -->
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<TextView
android:id="@+id/title"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="@id/favorite"
app:layout_constraintTop_toTopOf="parent" />
<CheckBox
android:id="@+id/favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>Predict the output
A RecyclerView shows 1,000 rows; about 10 fit on screen. The user scrolls from the top to the bottom. Roughly how many times is onCreateViewHolder called?
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
created++
return Holder(ItemRecipeBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}RecyclerView creates ViewHolders only until it has enough to cover the visible area plus a small cache, then recycles them. onBindViewHolder runs about 1,000 times, once for each row that appears, but onCreateViewHolder (which inflates XML, the expensive part) runs only a dozen or so times. That's why binding must be cheap and must reset everything.
The checkbox that ticks itself
Tap the line with the bug.
override fun onBindViewHolder(holder: Holder, position: Int) {
val recipe = getItem(position)
holder.binding.title.text = recipe.name
if (recipe.isFavorite) {
holder.binding.favorite.isChecked = true
}
holder.binding.favorite.setOnCheckedChangeListener { _, checked ->
onFavorite(recipe, checked)
}
}Hint: This ViewHolder showed a favorite recipe a moment ago. What does the checkbox show for a recipe that isn't a favorite?
The code only ever sets the checkbox to true. When a ViewHolder that showed a favorite is recycled for a recipe that isn’t one, nothing unchecks it, so the new row looks favorited. And when the code does set isChecked, the listener from the previous binding is still attached and fires, saving the old recipe’s state.
Set every property on every bind, and detach the listener while you do:
holder.binding.favorite.setOnCheckedChangeListener(null)
holder.binding.favorite.isChecked = recipe.isFavorite
holder.binding.favorite.setOnCheckedChangeListener { _, checked -> onFavorite(recipe, checked) }The same rule applies to images (clear or replace them, and cancel the old image request), visibility and colors: if you set it for some rows, set it for all.
Deep diveinvalidate() vs requestLayout()Interview favorite
invalidate() marks a view as needing to be redrawn: on the next frame its onDraw runs again, with the same size and position. Use it when only the appearance changes: a color, a progress arc, a custom chart’s highlighted bar.
requestLayout() marks the view and all its ancestors as needing measure and layout: on the next frame, the whole path to the root is measured and laid out again, and siblings may move. Use it when the view’s size might change: new text in a wrap_content view, a different image size. Setters like TextView.setText call it for you when needed. Calling requestLayout() from onLayout or on every animation frame forces layout passes on every frame, which shows up in a Perfetto trace as long “measure” and “layout” slices; animate translationX, alpha or scaleX instead, which only redraw.
- Measure (MeasureSpec), layout, draw;
invalidate= redraw,requestLayout= re-measure up the tree. FlatConstraintLayouttrees; nested weights andRelativeLayoutmeasure twice per level. - RecyclerView: pooled ViewHolders per view type, bind everything (state, listeners, images),
ListAdapter+DiffUtilwith stable ids and payloads instead ofnotifyDataSetChanged. - ViewBinding over
findViewById; synthetics are gone. View state is saved only for views with ids.
Check this part
Why must onBindViewHolder set every property of the row, even ones that look like defaults?
What replaced findViewById and Kotlin synthetics?
A custom view only changes color. Which call is enough?
What does ListAdapter with DiffUtil give you over notifyDataSetChanged()?