private void changePage(int position, SliderItem item) { mIgnoreBackStack = true; if (mCurrentPage >= 0) { final SliderItem lastItem = mAdapter.getItem(mCurrentPage); final WeakReference<Fragment> ref = lastItem.mLastFragment; final Fragment fragment = ref == null ? null : ref.get(); if (fragment != null && fragment.isAdded() && lastItem.mSaveState) { if (!fragment.isDetached()) { mFragmentManager.beginTransaction().detach(fragment).commit(); mFragmentManager.executePendingTransactions(); } lastItem.mSavedState = mFragmentManager.saveFragmentInstanceState(fragment); } } mCurrentPage = position; mAdapter.notifyDataSetInvalidated(); while (mFragmentManager.popBackStackImmediate()) {} final Fragment fragment = Fragment.instantiate(item.mFragmentClass); if (item.mSavedState != null) { fragment.setInitialSavedState(item.mSavedState); } item.mLastFragment = new WeakReference<Fragment>(fragment); replaceFragment(mFragmentManager, fragment); mIgnoreBackStack = false; }
@Override public void onBackStackChanged() { if (mIgnoreBackStack || mCurrentPage < 0 || mCurrentPage >= mItems.size()) { return; } SliderItem item = mItems.get(mCurrentPage); WeakReference<Fragment> ref = item.mLastFragment; Fragment fragment = ref == null ? null : ref.get(); if (fragment == null || !item.mSaveState) { return; } if (fragment.isAdded() && fragment.isDetached() && !fragment.isVisible()) { item.mSavedState = mFragmentManager.saveFragmentInstanceState(fragment); } }