Programmatically go back to the previous fragment in the backstack
Solution 1
Look at the getFragmentManager().popBackStack()
methods (there are several to choose from)
http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()
Solution 2
To elaborate on the other answers provided, this is my solution (placed in an Activity):
@Override
public void onBackPressed(){
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
Solution 3
When we are updating/add the fragments,
Should Include the .addToBackStack()
.
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail") // Add this transaction to the back stack (name is an optional name for this back stack state, or null).
.addToBackStack(null)
.commit();
After that if we give the getFragments.popBackStackImmediate()
will return true if we add/update the fragments, and move back to the current screen.
Solution 4
Android Navigation architecture component.
The following code works for me:
findNavController().popBackStack()
Solution 5
These answers does not work if i don't have addToBackStack() added to my fragment transaction but, you can use:
getActivity().onBackPressed();
from your any fragment to go back one step;
Related videos on Youtube
Aske B.
Updated on July 08, 2022Comments
-
Aske B. almost 2 years
Say I have an activity that has fragments added programmatically:
private void animateToFragment(Fragment newFragment, String tag) { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.fragment_container, newFragment, tag); ft.addToBackStack(null); ft.commit(); }
What is the best way to return to the previous fragment that was visible?
I found Trigger back-button functionality on button click in Android but I'm thinking simulating a back key event isn't the right way to go about it (and I can't get it to work either):
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
Calling
finish()
just closes the activity which I'm not interested in.Is there a better way to go about this?
-
Aske B. about 12 years
getFragmentManager().popBackStackImmediate();
did the trick. Thanks. -
rasen58 over 11 yearsWhere would I put this method though? In my tab listener?
-
stuckless over 11 yearswithout seeing the code, it's hard to say... but it should go in the section of code that is executed when you want to "close" the current fragment and return to the previous fragment.
-
ViliusK about 11 yearswhat about getSupportFragmentManager()
-
Murtaza Khursheed Hussain over 10 yearsand why is that happening. In fragment example developer.android.com/training/basics/fragments/index.html they are not overiding onbackpressed event and yet they are able to backstack fragment. I have used trasaction.addToBackStack(null); but nothing happens. Can you explain why ?
-
Kyle Falconer over 10 years@MurtazaHussain you should probably ask a new question if you want help with this. It's a little hard to see what's going on without looking at more code.
-
Abhijit Chakra over 10 years@alicanbatur yes you need to use addTOBackStack().
-
Gokhan Arik about 9 yearsWhat if we want to go to a fragment second or third previous. I visited fragments A->B->C->D and I want to go back to A or B from D?
-
stuckless about 9 yearsuse popBackStack("A", flags) (see developer.android.com/reference/android/app/…, int))
-
Facundo Olano almost 9 yearsIn my case I had to do
fm.getBackStackEntryCount() > 1
in order to call the activity back when there is only the first fragment in the stack. -
Khaled Saifullah over 8 yearsDon't forget to add "addToBackStack("tag")" in your code. "fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).addToBackStack("tag").commit();" if you write addToBackStack(null) , it will handle it by itself but if you give a tag , you should handle it manually.
-
Admin over 8 yearsNot seems works. in 2016, into setNavigationOnClickListener not works.
-
artkoenig over 7 yearsAndroid already do this for you: "When there are FragmentTransaction objects on the back stack and the user presses the Back button, the FragmentManager pops the most recent transaction off the back stack and performs the reverse action (such as removing a fragment if the transaction added it)." (Source)
-
Faisal Naseer about 6 years
popBackStackImmediate
is slower thanpopBackStack
in order to avoid performance issues usepopBackStack
where ever possible. -
CoolMind almost 6 yearsI think, TAG doesn't affect, it even maybe null.
-
AtifSayings over 4 yearsSimilar question is already answered. stackoverflow.com/questions/10863572/…
-
Alberto M about 4 yearsthe answer is now deprecated, you should use
getSupportFragmentManager().popBackStack()
-
Ayxan Haqverdili almost 4 years
requireActivity().onBackPressed()
for Kotlin -
John Glen over 3 yearsThis sends me back to the first fragment.
-
acmpo6ou over 3 yearsin kotlin you should use
supportFragmentManager().popBackStack()
-
Kraigolas over 3 yearsNote that if you're using navigation, this will work in getting you back but if you then try to navigate to the fragment that you popped, you'll encounter an error about not being able to navigate from the current destination. Instead, use
findNavController().navigateUp()
. -
karan_for_you over 3 yearsThis method comes in handy when you are using a custom designed toolbar. Works like a charm.
-
Andy Weinstein over 3 yearsIf you are using the navController I think you have to use this method - I first tried the fragment manager (the answer above) and got a crash when later trying to navigate using navController.