Junior — Middle
Can you describe the key specifics of using ViewHolder in lists and adapters?
sobes.tech AI
Answer from AI
ViewHolder is a pattern used in Android to optimize list operations (such as ListView or RecyclerView). Its main purpose is to avoid multiple calls to findViewById during list scrolling, which significantly improves performance.
Key features of using ViewHolder:
- Caching references to Views: Instead of searching for layout elements each time, the ViewHolder stores references to the necessary Views within a list item.
- Reusing Views: When scrolling the list, the adapter reuses already created Views, and the ViewHolder helps quickly update the content.
- Reducing GC load: Fewer object creations and calls to findViewById reduce the load on the garbage collector.
Example for RecyclerView:
class MyAdapter(private val items: List<String>) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView: TextView = itemView.findViewById(R.id.textView)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.textView.text = items[position]
}
override fun getItemCount() = items.size
}
Here, MyViewHolder stores a reference to the TextView, which allows for quick data updates without repeated View searches.