Corbella
Corbella

Reputation: 1812

Keep fragments on activity lifecycle

Maybe I miss something about fragments, but I can't understand this behave:

I have an Activity with a FrameLayout that contains a fragment. As normal, the activity is destroyed every time I Change Orientation creating a new FrameLayout instance. But I don't want the fragment to be created again, I want to keep the same fragment instance, as it needs a lot of time to load.

What I'm doing is the following (Assuming the FrameLayout has id=324):

    FragmentManager mng = getFragmentManager();
    Fragment frag = (Fragment)mng.findFragmentByTag(DEFAULT_TAG);

    //I create a new fragment if it doesn't exist or I remove the fragment from any view that is attached if it existed
    if (frag==null) frag = new MyFragment();
    else mng.beginTransaction().remove(frag).commit();

    //I add the fragment to the newly created FrameLayout
    mng.beginTransaction().add(324, frag, DEFAULT_TAG).commit();

It crashes:

08-09 11:54:38.970: E/AndroidRuntime(2517): Caused by: java.lang.IllegalArgumentException: Binary XML file line #15: Duplicate id 0x7f050016, tag null, or parent id 0xffffffff with another fragment for com.test.PRMapFragment
08-09 11:54:38.970: E/AndroidRuntime(2517):     at android.app.Activity.onCreateView(Activity.java:4248)

The first time goes all ok, but when rotating the screen, it crashes. It complains about a fragment inside MyFragment, but has no sense, as the fragment hasn't changed.

Upvotes: 0

Views: 3461

Answers (1)

Alex MDC
Alex MDC

Reputation: 2456

Have a look at Fragment.setRetainInstance(): http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)

If you set this to true, it changes the fragment lifecycle so that it doesn't get destroyed and re-created along with the activity, instead it just gets detached and re-attached to the new activity. It hooks in to the activity's onRetainNonConfigurationInstance() callback to keep the object alive between configuration changes.

I have used this several times with invisible fragments, to allow long-running operations to work across configuration changes. I haven't tried it in a visible fragment with a view, but with some care you should be able to use it.

Upvotes: 2

Related Questions