Listen to ViewHolders in RecyclerView being recycled

Viewed 301

Is it possible to register a listener with a RecyclerView so that I can be notified whenever a a view within a ViewHolder is recycled i.e. onBindViewHolder(~) called?

I do not have the ability to modify the RecyclerView or the attached Adapter (if there is one).

1 Answers

You can use a lambda function on Adapter's constructor and listen onViewRecycled method of ListAdapter or RecyclerView.Adapter

class MyAdapter(val onViewRecycled:(Int) -> Unit) :
        ListAdapter<Any, CustomViewHolder>(AnyDiffCallback()) {



    override fun onViewRecycled(holder: CustomViewHolder) {
        super.onViewRecycled(holder)
        onViewRecycled(holder.absoluteAdapterPosition)
        
    }
}

If you cannot access adapter then you can use addOnChildAttachStateChangeListener with RecyclerView

recyclerView.addOnChildAttachStateChangeListener(object:
            RecyclerView.OnChildAttachStateChangeListener {
            override fun onChildViewDetachedFromWindow(view: View) {

            }

            override fun onChildViewAttachedToWindow(view: View) {

            }

        })
Related