且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

处置后,如何从RecyclerView的ViewHolders中删除OnClickListener?

更新时间:2023-12-04 21:19:22

如果您想在视图离开屏幕时设置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.