Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pop fragment off backstack

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.

like image 736
user2085335 Avatar asked Feb 20 '13 03:02

user2085335


People also ask

Does popBackStack destroy fragment?

FragmentManager popBackStack doesn't remove fragment.

What is popBackStack inclusive?

popBackStack(backStackId, INCLUSIVE) will pop all the fragments (states) back to backStackId, so once you pop the lowest i that you're going to pop, all the higher ones should get popped at the same time.

What is FragmentManager?

FragmentManager is the class responsible for performing actions on your app's fragments, such as adding, removing, or replacing them, and adding them to the back stack.


2 Answers

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);     } }); 
like image 141
Archie.bpgc Avatar answered Oct 01 '22 06:10

Archie.bpgc


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

like image 28
MohammedAli Avatar answered Oct 01 '22 06:10

MohammedAli