I'm converting a bunch of Views to use the ViewHolder pattern in RecyclerView instead. I have code that needs to be run in onAttachedToWindow() and onDetachedFromWindow(), or whatever's closest to it in terms of the View lifecycle. What can I do to replicate that?
We can implement View.OnAttachStateChangeListener
in our ViewHolder
:
class SomeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
View.OnAttachStateChangeListener {
...
init {
itemView.addOnAttachStateChangeListener(this)
}
override fun onViewDetachedFromWindow(v: View?) {
// Do what you need
}
override fun onViewAttachedToWindow(v: View?) {
// Do what you need
}
}
In Adapter
we set view in onCreateViewHolder(...)
:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SomeViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.some_item, parent, false)
return SomeViewHolder(view)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.