Android RecyclerView lifecycle – preservation of data etc

  android, android-recyclerview

A few somewhat unrelated questions regarding RecyclerView and how it appears to be behaving.

Setup, a normal Recycler/Adapter/and LiveData situation:

  1. FragmentA initializes a member mRecyclerAdapter in onCreateView(). Eventually a LiveData observe adds data to the list inside of this adapter. Normal stuff, the user scrolls, more data is added (pagination) etc.

  2. FragmentA navigates to FragmentB via NavController.navigate, then the users presses the back button to return to FragmentA.


A) When returning to FragmentA, onCreateView() is called again, in that function of course is all the original code of creating the member mRecyclerAdapter, adding it to the RecyclerView, etc. So…how is it even though I am calling new MyRecyclerAdapter() that the RecyclerView in the fragment still has the correct list full of paginated results and scroll position? I suppose it could be getting the list from the ViewModel which is preserving the list of queried data, but the scroll position?

B) When returning to FragmentA, the mRecyclerAdapter seems to be calling onBindViewHolder() again on all ViewHolders inside the RecyclerView. This causes my custom code to fade in images, show some animations, etc. I do not want this to occur when navigating back from FragmentB to FragmentA. I essentially want to make it seem as if FragmentA was just moved off to the side, not (as it seems) moved off to the side and cleared, thus having to re-bind (and re-animate/load) all data. Possible? Way to determine difference between "normally" adding new ViewHolders vs re-visitng an old Fragment on the backstack?

C) Is there any sort of cleanup/proper practice in handling RecyclerView/Adapter/LiveData in the lifecycle of a Fragment? In all the example code I’ve seen it seems this stuff is all initialized/observed in onCreateView() and never "cleaned up" (onDestroy() onPause()?)

Source: Android Questions