How can I detect recycling from within a recyclerView adapter, so I can perform an action before it gets recycled?

为君一笑 提交于 2021-02-11 14:40:50

问题


I have a recyclerview that contains fields with editTexts. When scrolling, the data in the edit texts gets all mixed up or erased due to some functions I use and the views being recycled. This could be completely solved if I could save my data before the view gets recycled. How can I detect that happening from WITHIN the adapter?


回答1:


Just add below code in your adapter's onBindViewHolder method:

viewHolder.setIsRecyclable(false);

so you never lose your data on the scroll.




回答2:


The appropriate way to do this is through setting a TextWatcher to your EditText and save the text passed on onTextChanged to your RecyclerView model and retrieve it when you're binding your view again but if you wish to do it when the view id getting recycled, you have to override the onViewRecycled method on your adapter:

@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
    ...
}

Note that in order to get notified of view recycling when recreating the views you also need to set a null adapter to your RecyclerView. Here is an example using a fragment:

@Override
public void onDestroyView() {
    super.onDestroyView();
    mRecyclerView.setAdapter(null);
}



回答3:


Android RecyclerView adapter has function's called,

onViewAttchedToWindow();

onViewDetachedFromWindow();

onViewRecycled();

Use this function's to achieve.




回答4:


While setting the data in Views inside onBindViewHolder() method use vh.setIsRecyclable(false); it will restrict your views to be recycled.



来源:https://stackoverflow.com/questions/56945146/how-can-i-detect-recycling-from-within-a-recyclerview-adapter-so-i-can-perform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!