Saving fragments of the status box

I am trying to save state in fragments of a navigation box when I switch between different fragments in a navigation box. For example: I start with a snippet. Fire some events, and then go to fragment B. Then I want to see the same state of fragment A when I switch back to fragment A from fragment B.

I tried using onSavedInstanceState (Bundle savedInstanceState), but it is only called when the orientation changes in the fragment life cycle. A new fragment is created every time I switch to a new fragment, and I cannot figure out how to save data from the fragment and reload it with another visit.

I do not want to use backstack () either because it deletes all the fragments to the fragment that I want to restore.

The following shows how I call fragments in a box switch.

private void selectItem(int position) {

    Fragment fragment;
    String TAG;

    switch (position) {
    case 0:
        fragment = new FragmntA();
        TAG = "A";
        break;
    case 1:
        fragment = new FragmentB();
        TAG = "B";
        break;
    case 2:
        fragment = new FragmentC();
        TAG = "C";
        break;
    case 3:
        fragment = new FragmentD();
        TAG = "D";
        break;
    case 4:
        fragment = new FragmentE();
        TAG = "E";
        break;
    default:
        fragment = new FragmentA();
        TAG = "A";
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction ft = fragmentManager.beginTransaction();
    ft.replace(R.id.content_frame, fragment, TAG);
    ft.commit()

I do not know if there is any point in the life cycle of the fragment where I can save its state. Any help would be greatly appreciated. Thank.

+4
source share
2 answers

In order not to lose the state of your fragments when switching from one to another, you should do the β€œnew fragment ()” only once and save the instance in a global variable.

But this will not solve the problem of rotation. For a rotation problem you should read this => http://blog.sqisland.com/2014/06/navigationdrawer-creates-fragment-twice.html It’s not easy, but I have not found another way yet.

0
source

, newInstance - null, .

.

saveinstancestate.

0

Source: https://habr.com/ru/post/1536367/


All Articles