问题
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