Home » Android » The difference between, onViewRecycled, onDetachedFromRecyclerView, and onViewDetachedFromWindow in Android

The difference between, onViewRecycled, onDetachedFromRecyclerView, and onViewDetachedFromWindow in Android

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m having some trouble understanding the terminology used by the official documentation. Specifically, there are the methods
onViewRecycled, onDetachedFromRecyclerView and
onViewDetachedFromWindow. What are the difference between these three?

How to&Answers:

There is a significant difference, even in their signature:

onDetachedFromRecyclerView(RecyclerView recyclerView) – Called by RecyclerView when it stops observing this Adapter.

What you might have not noticed, there is a matching method always called before this one:

onAttachedToRecyclerView(RecyclerView recyclerView) – Called by RecyclerView when it starts observing this Adapter.

When you call recyclerView.setAdapter(adapter), adapter receives call to onAttachedToRecyclerView(recyclerView). Then following call to recyclerView.setAdapter() will trigger adapters onDetachedFromRecyclerView(recyclerView).

You usually don’t need to override this method except for some special circumstances (like keeping count of observed recyclerViews etc.).


onViewRecycled(VH holder) is much simpler, it’s called before sending viewHolder to recycleViewPool.

You can think of it as a “cleanup” method of onBindViewHolder(VH holder, int position).


onViewDetachedFromWindow(VH holder) always follows a matching onViewAttachedToWindow(VH holder). It’s called in exact moment when viewholder is becoming visible or invisible (attach/detach calls).

If a viewHolder was detached but not recycled yet, it’s possible it can receive onViewAttachedToWindow(ViewHolder) call again without needing to rebind data with onBindViewHolder.