Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 906
pricks Avatar asked Jun 27 '18 18:06

pricks


1 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(null) 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 or 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.

like image 199
Pawel Avatar answered Nov 12 '22 12:11

Pawel