0

Hello I am working with sliding menu with fragment. Indivisual fragment works properly. But suppose user navigates From fragment A->B , now 'B' works perfect and now if user goes from B->A than fragment 'A' is called from onAttach() .

I want such a condition if any fragment is opened , than reopening it should not load whole fragment , it should be resumed just like we handle activity with Intent.FLAG_ACTIVITY_REORDER_TO_FRONT.

Here is my code...

FragmentManager fm = MainActivity.this.getSupportFragmentManager(); 
FragmentTransaction ft = fm.beginTransaction();  
Layout1 fragment = new Layout1();  
ft.add(R.id.activity_main_content_fragment, fragment,Layout1.class.getName());
ft.addToBackStack(Layout1.class.getName());
ft.commit();
Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
Mind Android
  • 558
  • 2
  • 9
  • 27
  • `FragmentTransaction t = fragMgr.beginTransaction(); t.hide(fragMgr.findFragmentByTag("stack"));` use this one it will just hide the fragment...when u press key down it will load from saved state – bGorle Feb 18 '14 at 11:03
  • You solved this problem ? –  Mar 09 '16 at 14:40

1 Answers1

2

Answer updated:

Reading the documentation, there is a way to pop the back stack based on either the transaction name or the id provided by commit. Using the name may be easier since it shouldn't require keeping track of a number that may change and reinforces the "unique back stack entry" logic.

Since you want only one back stack entry per Fragment, make the back state name the Fragment's class name (via getClass().getName()). Then when replacing a Fragment, use the popBackStackImmediate() method. If it returns true, it means there is an instance of the Fragment in the back stack. If not, actually execute the Fragment replacement logic.

private void replaceFragment (Fragment fragment){
  String backStateName = fragment.getClass().getName();

  FragmentManager manager = getSupportFragmentManager();
  boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);

  if (!fragmentPopped){ //fragment not in back stack, create it.
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.addToBackStack(backStateName);
    ft.commit();
  }
}

If you return to a fragment from the back stack it does not re-create the fragment but re-uses the same instance and starts with onCreateView() in the fragment lifecycle, see Fragment lifecycle.

So if you want to store state you should use instance variables and not rely on onSaveInstanceState()

Check this link. it will help How to resume Fragment from BackStack if exists

Community
  • 1
  • 1
Hassaan Rabbani
  • 2,469
  • 5
  • 30
  • 55
  • 1
    I don't think you should negate fragmentPopped. Shouldn't it be like this? if (fragmentPopped) { – bogdan Aug 12 '14 at 14:48