If the adapter lives any longer than the RecyclerView
does, you’ve got to clear the adapter reference in onDestroyView
:
@Override
public void onDestroyView() {
recyclerView.setAdapter(null);
super.onDestroyView();
}
Otherwise the adapter is going to hold a reference to the RecyclerView
which should have already gone out of memory.
Special note prior to androidx.fragment:fragment:1.3.0:
If the screen is involved in transition animations, you actually have to take this one step further and only clear the adapter when the view has become detached:
@Override
public void onDestroyView() {
recyclerView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View v) {
// no-op
}
@Override
public void onViewDetachedFromWindow(View v) {
recyclerView.setAdapter(null);
}
});
super.onDestroyView();
}
With androidx.fragment:fragment:1.3.0
and above, onDestroyView
happens after the view is detached and this extra code is no longer needed.