Interview frequency: …
Short answer
It recycles the views that leave the screen to show new items instead of creating them from scratch, which prevents repeated findViewById calls.
Explanation
The ViewHolder keeps references to the UI elements in memory. While scrolling, the RecyclerView does not create a new View; it only calls onCreateViewHolder enough times to fill the screen with a small margin, then reuses these containers through onBindViewHolder to update only the texts and images, which provides very smooth scrolling at 60/120 frames per second.
Code example
class UserAdapter : RecyclerView.Adapter<UserAdapter.UserViewHolder>() {
class UserViewHolder(val binding: ItemUserBinding) : RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val binding = ItemUserBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return UserViewHolder(binding)
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
holder.binding.nameText.text = items[position].name
}
}Common mistakes
- Performing costly processing or complex computations inside onBindViewHolder, causing noticeable stutter while scrolling.
- Forgetting to set setHasFixedSize(true) when the list's dimensions are fixed and independent of its contents.