Prevent Fragment recovery in Android

前端 未结 7 1679
星月不相逢
星月不相逢 2020-12-07 22:53

We are using Fragments and we don\'t need them to be automatically recovered when the Activity is recreated. But Android every time when Activity::onCreate(Bundle save

相关标签:
7条回答
  • 2020-12-07 23:18

    View hierarchy in not restored automatically. So, in Fragment.onCreateView() or Activity.onCreate(), you have to restore all views (from xml or programmatically). Each ViewGroup that contains a fragment, must have the same ID as when you created it the first time. Once the view hierarchy is created, Android restores all fragments and put theirs views in the right ViewGroup thanks to the ID. Let say that Android remembers the ID of the ViewGroup on which a fragment was. This happens somewhere between onCreateView() and onStart().

    0 讨论(0)
  • 2020-12-07 23:20

    Those who got NPE with ViewPager when use this method described in the accepted answer, please override

    ViewPager.onRestoreInstanceState(Parcelable state)

    method and call

    super.onRestoreInstanceState(null);

    instead.

    0 讨论(0)
  • 2020-12-07 23:21

    I removed the fragments in Activity's onCreate.

    0 讨论(0)
  • 2020-12-07 23:21

    For an app with a ViewPager, I remove the fragments in onCreate(), before their creation.

    Based on this thread: Remove all fragments from container, we have:

    FragmentManager fm = getSupportFragmentManager();
    for (Fragment fragment: fm.getFragments()) {
      fm.beginTransaction().remove(fragment).commitNow();
    }
    
    0 讨论(0)
  • 2020-12-07 23:28

    We finished by adding to activity:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(null);
    }
    

    It suppresses any saved data on create/recreate cycle of an Activity and avoids fragments auto re-creation.

    0 讨论(0)
  • 2020-12-07 23:31

    @goRGon 's answer was very useful for me, but such use cause serious problems when there is some more information you needs to forward to your activity after recreate.

    Here is improved version that only removes "fragments", but keep every other parameters.

    ID that is removed from bundle is part of android.support.v4.app.FragmentActivity class as FRAGMENTS_TAG field. It may of course change over time, but it's not expected.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(createBundleNoFragmentRestore(savedInstanceState));
    }
    
    /**
     * Improve bundle to prevent restoring of fragments.
     * @param bundle bundle container
     * @return improved bundle with removed "fragments parcelable"
     */
    private static Bundle createBundleNoFragmentRestore(Bundle bundle) {
        if (bundle != null) {
            bundle.remove("android:support:fragments");
        }
        return bundle;
    }
    
    0 讨论(0)
提交回复
热议问题