正在GroceryFragment中保存onPause()处的RecyclerView状态:
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause: called");
FragmentStateListener fragmentStateListener = (FragmentStateListener) getActivity();
fragmentStateListener.savingFragmentState(mCategoriesRV.getLayoutManager().onSaveInstanceState(), GROCERY_FRAGMENT);
Log.d(TAG, "onPause: state - " + mCategoriesRV.getLayoutManager().onSaveInstanceState());
}
下面是接口fragmentStateListener:
public interface FragmentStateListener {
public void savingFragmentState(Parcelable parcelable, int fragmentInt);
}
此接口正在由HomeActivity实现:
@Override
public void savingFragmentState(Parcelable parcelable, int fragmentInt) {
Log.d(TAG, "savingFragmentState: parcelable = " + parcelable);
Log.d(TAG, "savingFragmentState: fragmentInt = " + fragmentInt);
switch (fragmentInt) {
case HomeFragment.HOME_FRAGMENT:
mHomeFragmentSavedState = parcelable;
break;
case GroceryFragment.GROCERY_FRAGMENT:
mGroceryFragmentSavedState = parcelable;
break;
}
}
而且由于GroceryFragment是BrowseFragment中嵌套的ViewPager片段,因此首先将此Parcelable值传输到BrowseFragment,然后从那里传输到GroceryFragment:
case R.id.browse_menu_item :
Log.d(TAG, "onNavigationItemSelected: browse icon clicked");
mBottomNavigationViewBNV.enableShiftingMode(1, false);
toggleChangeBottomNavigationItemIconsColor (1, 0, 2, 3, 4);
replaceFragment(BrowseFragment.newInstance(null, null, mGroceryFragmentSavedState), R.id.fragments_container_CL);
break;
...
fragmentList.add(GroceryFragment.newInstance(null, null, mGroceryFragmentSavedState));
以下是GroceryFragment中的newInstance方法:
public static GroceryFragment newInstance(String param1, String param2, Parcelable savedState) {
GroceryFragment fragment = new GroceryFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
args.putParcelable(RECYCLERVIEW_STATE, savedState);
Log.d(TAG, "newInstance: savedstate = " + savedState);
fragment.setArguments(args);
return fragment;
}
GroceryFragment的onCreate()方法:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
mSavedState = getArguments().getParcelable(RECYCLERVIEW_STATE);
}
}
最后将savedstate还原到recyclerview的layoutmanager:
mCategoriesRV.setHasFixedSize(true);
CategoriesRecyclerAdapter categoriesRecyclerAdapter =
new CategoriesRecyclerAdapter(getFirestoreRecyclerOptions (), getActivity(), GroceryFragment.this, mCategoriesCL);
mCategoriesRV.setAdapter(categoriesRecyclerAdapter);
categoriesRecyclerAdapter.startListening();
mCategoriesRV.setLayoutManager(new GridLayoutManager(getActivity(), 2));
if(mSavedState != null) {
Log.d(TAG, "mCategoriesRVAction: mSavedState = " + mSavedState);
mCategoriesRV.getLayoutManager().onRestoreInstanceState(mSavedState);
}
上述代码的logcat屏幕截图,其中清楚地显示msavedstate不是空的,但它仍在恢复状态: