Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove OnClickListeners from RecyclerView's ViewHolders when they are disposed?

Tags:

I am using RecyclerViews in my app project and setting OnClickListeners with their ViewHolders (in their constructors like mentioned in a StackOverflow Q&A).

Then I have this question: how can I remove OnClickListeners from RecyclerView's ViewHolders when they are disposed.

Usually, we can remove an OnClickListener by doing this:

view.setOnClickListener(null); 

And if it is a ViewPager's PagerAdapter, we can do so in destroyItem method.

@Override public void destroyItem(ViewGroup container, int position, Object object) {     View view = container.findViewById(R.id.viewId);     view.setOnClickListener(null); } 

Where can I do so with RecyclerView? --Or, I need not do so?

like image 466
hata Avatar asked Nov 21 '15 17:11

hata


People also ask

When onViewRecycled is called?

onViewRecycled() : Once a ViewHolder is successfully recycled, onViewRecycled gets called. This is when we should release resources held by the ViewHolder.


2 Answers

If you want to null set the onCLickListener() of the views of RecyclerView.Adapter when the view goes off the screen, you can do so by overriding the http://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#onViewDetachedFromWindow(VH) in your recyclerView's adapter. You will receive the holder as parameter that has just gone off the screen. You can null set onClickListener of any view available in that holder.

Or if you just want to do the same when it becomes visible on the screen, you can do in onBindViewHolder(). But this does not make sense as instead you can avoid setting listener.

Points to remember, related to this answer:
Setting the listener to null may be ther requirement when you do not want to set click listener to view for every data set but to only few. In this case, it is always better to set listenrs to null as and when they go off the screen. Otherwise, as RecyclerView will re-use (recycle) the holder objects that were gone away to represent the new dataset that is becoming visible. In this process, data set (view in a holder) that you did not set the listener to may have the listener set because of recycling.

All in all, while getting the advantage of smooth scrolling due to recycling, it is dev's responsibility to reset the views (clearing image views, text views etc..) and null setting the onCLickListener etc.

like image 120
cgr Avatar answered Oct 21 '22 19:10

cgr


If you are using RecyclerView and binding OnClickListeners to it's every row root view, there is no need to dispose them.

But if some views shouldn't respond to click event's just use setOnClickListener(null)

like image 29
michal.luszczuk Avatar answered Oct 21 '22 18:10

michal.luszczuk