Search code examples
androidandroid-fragmentstransactionssavestate

saving fragment transaction whereever


initially I have an activity A in which I'm gonna open one fragment so here how can i save that fragment So, that when I launch my application after destroying it restores that fragment in that same Activity in same position

For, answering convenience here's my fragment transaction code:

    Fragment newFragment = new ece_frag();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.setCustomAnimations(R.anim.fade_in,R.anim.fade_out);
    transaction.replace(R.id.frame_layout, newFragment);
    transaction.commit();

Solution

  • Lets say you have 3 fragments A,B and C.

    I give index to each fragment like this say 0->A, 1->B, 2->C. So when i do this, I also save the index like the code below:

    Fragment newFragment = new A();
    FragmentTransaction transaction = 
    getFragmentManager().beginTransaction();
    transaction.setCustomAnimations(R.anim.fade_in,R.anim.fade_out);
    transaction.replace(R.id.frame_layout, newFragment);
    transaction.commit();
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt("last_fragment", 0);//For fragment A saving index 0
    editor.commit();
    

    And then in onCreate you can use an if case like this:

    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    //0 here is the default value
    int lastFragment = sharedPref.getInt("last_fragment", 0);
    

    Then you can do this

    switch(lastFragment){
      case 0:
      //Load your fragment Here according to the index.
      break;
      case 1:
      //Load your fragment Here according to the index.
      break;
      case 2:
      //Load your fragment Here according to the index.
      break;
    
    }
    

    Hope this helps.