The posted solution works, but I'd like to add something to it. The purpose of the viewholder pattern is to only make the expensive findViewById
calls once for every view, and then hold those references inside the ViewHolder
, and access the views from there whenever you need to bind one.
However, calling holder.itemView.tv_title.text
in the onBindViewHolder
method will cause a findViewById
call to find the View
that has the id tv_title
within the itemView
every time the viewholder is bound. This basically eliminates the performance gains and caching idea that viewholders are for.
You can make use of the viewholder pattern and Kotlin Android Extensions at the same time by adding a property to your ViewHolder
, and initializing it with a call made with Extensions, like so:
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val title = itemView.tv_title
}
Then you can access the View
through this property:
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.title.text = mRooms!!.get(position).getLocation()
holder.itemView.setOnClickListener { v ->
mListener?.onItemClickListener(v, holder.layoutPosition)
}
}
Lastly, I'd suggest getting rid of the !!
operator, and performing a null check instead:
mRooms?.let { rooms ->
holder.title.text = rooms[position].getLocation()
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…