Prevent Fragment recovery in Android

南笙酒味 提交于 2019-11-28 04:31:27

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.

@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;
}

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.

I removed the fragments in Activity's onCreate.

I also had a ViewPager so I checked the fragmentMananger if it had fragments in it and removed them in onCreate().

Using for example this thread: Remove all fragments from container.

FragmentManager fm = getSupportFragmentManager();
for (Fragment fragment: fm.getFragments()) {
  fm.beginTransaction().remove(fragment).commitNow();
}

commitNow() to remove fragments synchronosly.

I was having a problem with TransactionTooLargeException. So thankfully after using tolargetool I founded that the fragments (android:support:fragments) were been in memory, and the transaction became too large. So finally I did this, and it worked great.

@Override
public void onSaveInstanceState(final Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("android:support:fragments", null);
}
user2982482

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().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!