简体   繁体   中英

Equivalent of onAttachedToWindow()/onDetachedFromWindow() for a ViewHolder in RecyclerView

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM