@Override public void finishUpdate(ViewGroup container) { if (mCurTransaction != null) { mCurTransaction.commitAllowingStateLoss(); mCurTransaction = null; mFragmentManager.executePendingTransactions(); for (Fragment fragment : mFragments) { if (fragment != null) { /* if (fragment.isAdded() && !fragment.isResumed()) { // Fix sdk 23.0.1 : Fragment isAdded, but didn't resumed. if (FragmentUtils.isStateLoss(fragment.getFragmentManager())) { continue; } // Test move to fixActiveFragment(mFragmentManager, fragment); // fragment.getFragmentManager().beginTransaction().detach(fragment).attach(fragment).commit(); } */ if (FragmentUtils.isStateLoss(fragment.getFragmentManager())) { continue; } // Fix sdk 22.0.1 : Fragment is added by transaction. BUT didn't add to FragmentManager's // mActive. If you Rotation. fixActiveFragment(mFragmentManager, fragment); } } } }
public static void fixActiveFragment(FragmentManager fragmentManager, Fragment fragment) { FragmentManagerImpl fm = (FragmentManagerImpl) fragmentManager; boolean needMatch = false; Fragment willRemoveFrag = null; if (fm.mActive != null) { int index = fragment.mIndex; if (index < 0) { Log.e(TAG, String.format("Fragment mIndex %s < 0 ! Origin: %s", fragment.mIndex, fragment)); fragment.getFragmentManager().beginTransaction().remove(fragment).commit(); return; } Fragment origin = fm.mActive.get(index); if (origin != null) { if ((origin.mIndex != fragment.mIndex) || !(origin.equals(fragment))) { Log.e( TAG, String.format( "Fragment isn't equal! Origin: %s %s, Fragment: %s %s", origin.toString(), origin.mIndex, fragment.toString(), fragment.mIndex)); ArrayList<Integer> indexArray = new ArrayList<>(); for (Fragment f : fm.mAdded) { if (indexArray.contains(f.mIndex)) { willRemoveFrag = origin; break; } indexArray.add(f.mIndex); } } } fm.mActive.set(index, fragment); if (willRemoveFrag != null) { // 2016.01.26 Fix bug mAdded not match // 瀏覽所有Fragment後,轉至後瀏覽其他Fragment會產生衝突 fm.mAdded.remove(willRemoveFrag); } // 如往回跳的話會發現沒有執行 // 1~5 is Fragment // 1 2 3 4 5 -> 3 // 1 2 3 -> 1 // v25.0.0 Fix fragment didn't run, if through step 1, 2, 3 then go back to 1, step 1 fragment // didn't run if (fragment.getUserVisibleHint() && !fragment.isResumed()) { if (!FragmentUtils.isStateLoss(fragment.getFragmentManager())) { fragment .getFragmentManager() .beginTransaction() .detach(fragment) .attach(fragment) .commit(); } } } }