android-fragmentsfragmentmanagerfragmenttransactionfragment-backstacksupportfragmentmanager

Popbackstack always returns previous call


I've got three Simple Fragments: FragmentA, FragmentB, FragmentC.

FragmentA -> FragmentB:

FragmentB fragment2 = new FragmentB ();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.mainLayout, fragment2);
fragmentTransaction.commit();

FragmentB -> FragmentC:

FragmentC fC= new FragmentC ();
FragmentManager fragmentManager =  getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.mainLayout, fC);
fragmentTransaction.addToBackStack("FragmentA");
fragmentTransaction.commit();

FragmentC -> FragmentA:

getActivity().getSupportFragmentManager().popBackStack("FragmentA",0);

The Issue is that I always return to FragmentB altough my aim is to return to FragmentA. What am I missing?


Solution

  • FragmentManager fmManager = getFragmentManager();
    if (fmManager.getBackStackEntryCount() > 0) { fmManager.popBackStack(fmManager.getBackStackEntryAt(fmManager.getBackStackEntryCount()-2).getId(), fmManager.POP_BACK_STACK_INCLUSIVE); }
    

    what this code does, it checks if there are stacked fragments. If yes, it gets the fragment at the first stake, which is fragmentA, and returns to this fragment. Whats important is that u are aware at which position the fragment is positioned!!