Junior — Middle
Explain the difference between onCreateViewHolder and onBindViewHolder methods in a RecyclerView adapter.
sobes.tech AI
Answer from AI
In a RecyclerView adapter, the methods onCreateViewHolder and onBindViewHolder serve different purposes:
-
onCreateViewHolderis called when a new ViewHolder object needs to be created. Here, the layout file of the list item is inflated, and a ViewHolder is created, which holds references to the necessary Views within that item. -
onBindViewHolderis called to bind data to an already created ViewHolder. In this method, you populate the interface elements with specific data from your dataset at the given position.
Example:
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) {
val item = dataList[position]
holder.textView.text = item.name
}
Thus, onCreateViewHolder is responsible for creating the View, and onBindViewHolder is responsible for filling the View with data.