Android RecyclerView ViewHolder — Complete Guide
In this tutorial, you'll learn about Android RecyclerView ViewHolder. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
You inflate a new layout in onBindViewHolder, hold references to the wrong views, or forget that ViewHolders are recycled and carry stale state.
Wrong Approach ❌
class MyAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
// Inflating in onBindViewHolder — terrible for performance
val view = LayoutInflater.from(holder.itemView.context)
.inflate(R.layout.item_user, null)
val name = view.findViewById<TextView>(R.id.name)
name.text = getItem(position)
}
}
Output: Janky scrolling, skipped frames, wasted memory.
Right Approach ✅
class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val name: TextView = itemView.findViewById(R.id.name)
private val avatar: ImageView = itemView.findViewById(R.id.avatar)
fun bind(user: User) {
name.text = user.name
Glide.with(itemView.context).load(user.avatarUrl).into(avatar)
// Clear pending state from recycling
itemView.setOnClickListener { /* handle click */ }
}
}
class MyAdapter : RecyclerView.Adapter<UserViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_user, parent, false)
return UserViewHolder(view)
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
holder.bind(items[position])
}
}
Output: Smooth scrolling with properly recycled views.
Prevention
- Always inflate layouts in
onCreateViewHolderonly. - Clear transient state (listeners, animations) in
onBindViewHolder. - Use
setIsRecyclable(false)only when absolutely necessary. - Cache view references in
ViewHolderfields — never usefindViewByIdinonBindViewHolder.
Common Mistakes with recyclerview viewholder
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro