89

I have an activity A, which calls fragment Bf, which calls fragment Cf. I want Bf to be placed in the backstack when Cf is called so that users can navigate back to it. However, if a specific button is pressed in Cf, I would like Bf to be removed from the backstack. Is this possible?

I see that there is a popBackStack() function. However, I am a little confused on how this would work. Is it safe to use this function? Is there any possibility that an activity from a different application would be inserted after Bf on the backstack?

Also, is there any way to alter the savedInstanceState of the fragment on the backstack?

I just can't figure out how to do a robust test on the backstack using the emulator.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
user2085335
  • 1,059
  • 1
  • 8
  • 11
  • Avoid using back stacks! it doesn't really help with the overall efficiency! use plain replace() or even better remove/add every time you want to navigate! Check my post on http://stackoverflow.com/questions/5802141/is-this-the-right-way-to-clean-up-fragment-back-stack-when-leaving-a-deeply-nest/26093368#26093368 – stack_ved Sep 29 '14 at 06:01
  • 2
    @stack_ved not a good idea. BackStacks are a great thing. Btw I can't see your post. I guess it was downvoted. :P – Sufian Nov 18 '16 at 15:04

5 Answers5

145

You can pop the fragment by name. While adding fragments to the back stack, just give them a name.

fragmentTransaction.addToBackStack("fragB");
fragmentTransaction.addToBackStack("fragC");

Then in Fragment_C, pop the back stack using the name ie.. fragB and include POP_BACK_STACK_INCLUSIVE

someButtonInC.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        FragmentManager fm = getActivity()
                .getSupportFragmentManager();
        fm.popBackStack ("fragB", FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
});
JJD
  • 50,076
  • 60
  • 203
  • 339
Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226
  • 15
    It will work even if we pass no parameters too in the fm.popBackStack Method. fm.popBackStack(); – Kailas Mar 06 '14 at 10:53
  • what if I want to make it on back button press? – Akshay Mar 15 '14 at 11:18
  • 1
    @Akki if you are using add to backstack it will already pop the last fragment added when you hit the back navigation item. So no extra steps are necessary to perform a normal navigation back. Only time you need to override on back button pressed is when you want to do something other than a normal one step back navigation. – ocross Jul 09 '14 at 19:44
  • 1
    What if that fragment was the first fragment, then `addToBackStack` with `replace` will cause a problem. Any way to do this without calling `addToBackStack`? – Hamzeh Soboh Apr 19 '15 at 09:52
  • 4
    According to doc "all states up to that state will be popped", not just a specific fragment. – Vahid Ghadiri Sep 02 '15 at 00:07
  • @VahidGhadiri That is how the Stack Data structure is designed. – Sreekanth Karumanaghat Aug 29 '17 at 10:36
26

Three ways to pop Fragment off BackStack

Simply add any of these lines:

1)

getActivity().getSupportFragmentManager().popBackStack();

2)

getActivity().getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

3)

getActivity().getSupportFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

They're all easy ways to pop fragment off Backstack

2hamed
  • 8,719
  • 13
  • 69
  • 112
MohammedAli
  • 2,361
  • 2
  • 19
  • 36
  • Thank you so muchhhhh! After overiding onbackpressed, this really helped me to go back. I searched for about an hour – KSDev Jul 02 '20 at 19:38
3

You can try this way

val fm= parentFragmentManager
fm.popBackStack("group", FragmentManager.POP_BACK_STACK_INCLUSIVE)
Anshul Nema
  • 281
  • 3
  • 3
1

first replacing fragment container_view that time we add name as like "Later Transaction"

   getSupportFragmentManager().beginTransaction().replace(R.id.container_view, 
    profileFragment, "Profile").addToBackStack("Later Transaction").commit();

then on back press button pop the back stack using the Later Transaction name

     int count = getSupportFragmentManager().getBackStackEntryCount();
    if(count > 1) {
     getSupportFragmentManager().popBackStack("Later Transaction", 
     FragmentManager.POP_BACK_STACK_INCLUSIVE);
    } else {
        DialogUtils.show(HomeActivity.this, 
        getString(R.string.exit_app_message), getString(R.string.alert), 
       "Yes","No", new DialogUtils.ActionListner() {
            @Override
            public void onPositiveAction() {
                finish();
            }
            @Override
            public void onNegativeAction() {
            }
        });
    }
Abhijit Rajmane
  • 173
  • 2
  • 12
0

Here's example to pop last fragment using BackStackEntry

val manager = supportFragmentManager
try {
    // get last entry (you can get another if needed)
    val entry = manager.getBackStackEntryAt(manager.backStackEntryCount - 1)
    // you can pop it by name
    manager.popBackStack(entry.name, FragmentManager.POP_BACK_STACK_INCLUSIVE)
    // or pop by id
    manager.popBackStack(entry.id, FragmentManager.POP_BACK_STACK_INCLUSIVE)
} catch (ex: Exception) {
    ex.printStackTrace()
}
Andrii Turkovskyi
  • 27,554
  • 16
  • 95
  • 105