Search code examples
androidandroid-fragmentsorientation-changes

How to retain Fragments from backstack on orientation changes?


How can I retain fragments from backstack on orientation changes?

I'm using this code to add fragments to backstack:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment, tag);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

But they disappear when I change device orientation.

I'm trying to reproduce the behavior of fragments in Google Play.


Solution

  • How can I retain fragments from backstack on orientation changes?

    AFAIK, you don't. Instead, you have other fragment(s), such as a model fragment, that you retain.

    Bear in mind that Google's official recommendation is for fragments with UI to never be retained, due to the risk of developers screwing up and holding onto things related to the old activity that they shouldn't. Personally, I think that recommendation is overkill.

    I'm trying to reproduce the behavior of fragments in Google Play.

    I am not quite certain what you are referring to here. There's no way from outside an app to determine if that app is retaining fragments or not.