问题描述
我在我的应用程序项目中使用RecyclerViews,并为其ViewHolders设置OnClickListeners(在其构造函数中,如StackOverflow Q&A ).
I am using RecyclerViews in my app project and setting OnClickListeners with their ViewHolders (in their constructors like mentioned in a StackOverflow Q&A).
然后我有一个问题:在处置RecyclerView的ViewHolders时,如何从它们中删除OnClickListeners.
通常,我们可以通过执行以下操作删除OnClickListener:
Usually, we can remove an OnClickListener by doing this:
view.setOnClickListener(null);
如果它是ViewPager的PagerAdapter,则可以使用destroyItem
方法来实现.
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);
}
在哪里可以使用RecyclerView? -或者,我不需要这样做吗?
Where can I do so with RecyclerView? --Or, I need not do so?
推荐答案
如果您想在视图离开屏幕时设置RecyclerView.Adapter视图的onCLickListener()为空,则可以通过覆盖 http://developer.android.com /reference/android/support/v7/widget/RecyclerView.Adapter.html#onViewDetachedFromWindow(VH)在您的recyclerView适配器中.您将收到刚刚离开屏幕的Holder作为参数.您可以将该持有人中可用的任何视图的onClickListener设置为空.
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.
或者,如果您只想在屏幕上看到它时执行相同的操作,则可以在onBindViewHolder()中进行.但这没有意义,因为您可以避免设置侦听器.
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.
要记住的要点,与该答案有关:
当您不想将单击侦听器设置为查看每个数据集而仅查看少数数据集时,可能需要将侦听器设置为null.在这种情况下,总是最好在离开屏幕时将监听器设置为null.否则,由于RecyclerView将重新使用(回收)已消失的Holder对象,以表示将变得可见的新数据集.在此过程中,未设置侦听器的数据集(在持有人中查看)可能由于回收而设置了侦听器.
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.
总而言之,尽管由于回收而获得了平滑滚动的优势,但开发人员有责任重置视图(清除图像视图,文本视图等),并为null设置onCLickListener等.
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.
这篇关于处置后,如何从RecyclerView的ViewHolders中删除OnClickListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!