I am Using the MVVM pattern with Room Database. In one of the Screen there are 3 Tabs with FragmentPagerAdapter viewPager. Now I am able to save and Retrieve from Database in My Fragments. But I also Want to save the Scroll state of Recycler Views which are inside all the 3 tabs.
So, Each fragment is going to Use a different Method to get LiveData from Dao. So each query is being observed by 1 Fragment Only. Now ViewPager has default value of viewPager.setOffscreenPageLimit(); is 1
by default. Now I want to save the scroll state of each fragment even after paused and coming back.
Below is the code for fragments to observe the Livedata which is common in all tabs:
mViewModel.getLiveFlights().observe(getViewLifecycleOwner(), flightGroups -> adapter.submitList(flightGroups));
I have Tried Saving the LinearLayoutManager State and retrieving it later by following code:
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
Log.e(TAG,"onViewStateRestored");
if(savedInstanceState != null)
{
Parcelable savedRecyclerLayoutState = savedInstanceState.getParcelable(BUNDLE_RECYCLER_LAYOUT);
if(savedRecyclerLayoutState != null && recyclerView.getLayoutManager() != null)
recyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerLayoutState);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.e(TAG,"onSaveInstanceState");
if(recyclerView.getLayoutManager() != null)
outState.putParcelable(BUNDLE_RECYCLER_LAYOUT, recyclerView.getLayoutManager().onSaveInstanceState());
}
EDIT: I got the above code using: https://stackoverflow.com/a/29166336