Alberto
Alberto

Reputation: 377

Managing fragments state

I'm having a headache with this.

The scenario is the following:

I have an Activity with a FrameLayout that hosts 4 Fragments.
I don't mind to recreate each time the fragments except for one of them.
There is one that I need to keep untouched.

Here is my navigation scheme:

Navigation scheme

The fragment I want to keep and not recreate is Frag A.

In my Activity I have this method for managing the fragments:

protected final static int FRAG_A=0;
protected final static int FRAG_B=1;
protected final static int FRAG_C=2;
protected final static int FRAG_D=3;

protected void displayNewFragment(int newFragment)
{
    Fragment fragment=null;
    String tag=null;

    switch(newFragment)
    {
        case FRAG_A:
            tag=FragA.TAG;
            fragment=new FragA();

            break;

        case FRAG_B:
            tag=FragB.TAG;
            fragment=new FragB();

            break;

        case FRAG_C:
            tag=FragC.TAG;
            fragment=new FragC();

            break;

        case FRAG_D:
            tag=FragD.TAG;
            fragment=new FragD();

            break;
    }

    if(fragment!=null)
        manager.beginTransaction().replace(R.id.main_container, fragment, tag).commit();
    else
        Log.e(getClass().getSimpleName(), "Error creating content (null).");
}

This method is called by fragments when I want to switch to another, being parent the reference to the activity (Main):

parent.displayNewFragment(Main.FRAG_A) // Or FRAG_B, C, D, etc

I know that I'm recreating each instance in that method and the previous is destroyed (as I call replace in the fragment transaction. This works perfect except for what I'm asking:
How to prevent destroying FragA and keep its state??

Thank you in advance.

Upvotes: 0

Views: 642

Answers (2)

Vijay Kumar M
Vijay Kumar M

Reputation: 182

To manage the fragments in your activity, you need to use FragmentManager. To get it, call getFragmentManager() from your activity.

Some things that you can do with FragmentManager include:

  • Get fragments that exist in the activity, with findFragmentById() (for fragments that provide a UI in the activity layout) or findFragmentByTag() (for fragments that do or don't provide a UI).

  • Pop fragments off the back stack, with popBackStack() (simulating a Back command by the user).

  • Register a listener for changes to the back stack, with addOnBackStackChangedListener().

Upvotes: 0

Dinesh R Rajput
Dinesh R Rajput

Reputation: 750

please use addToBackStack to prvent destroying fragment and keep its state as showing below:-

if(fragment!=null)
    manager.beginTransaction().replace(R.id.main_container, fragment, tag).addToBackStack("spartacus").commit();
else
    Log.e(getClass().getSimpleName(), "Error creating content (null).");

Cheers...!!! Please let me know if its work for you or not :)

Upvotes: 1

Related Questions