Programmatically go back to the previous fragment in the backstack

327,439

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;

Share:
327,439

Related videos on Youtube

Aske B.
Author by

Aske B.

Updated on July 08, 2022

Comments

  • Aske B.
    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.
    Aske B. about 12 years
    getFragmentManager().popBackStackImmediate(); did the trick. Thanks.
  • rasen58
    rasen58 over 11 years
    Where would I put this method though? In my tab listener?
  • stuckless
    stuckless over 11 years
    without 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
    ViliusK about 11 years
    what about getSupportFragmentManager()
  • Murtaza Khursheed Hussain
    Murtaza Khursheed Hussain over 10 years
    and 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
    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
    Abhijit Chakra over 10 years
    @alicanbatur yes you need to use addTOBackStack().
  • Gokhan Arik
    Gokhan Arik about 9 years
    What 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
    stuckless about 9 years
    use popBackStack("A", flags) (see developer.android.com/reference/android/app/…, int))
  • Facundo Olano
    Facundo Olano almost 9 years
    In 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
    Khaled Saifullah over 8 years
    Don't forget to add "addToBackStack("tag")" in your code. "fragmentManager.beginTransaction().replace(R.id.content_fra‌​me,fragment).addToBa‌​ckStack("tag").commi‌​t();" if you write addToBackStack(null) , it will handle it by itself but if you give a tag , you should handle it manually.
  • Admin
    Admin over 8 years
    Not seems works. in 2016, into setNavigationOnClickListener not works.
  • artkoenig
    artkoenig over 7 years
    Android 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
    Faisal Naseer about 6 years
    popBackStackImmediate is slower than popBackStack in order to avoid performance issues use popBackStack where ever possible.
  • CoolMind
    CoolMind almost 6 years
    I think, TAG doesn't affect, it even maybe null.
  • AtifSayings
    AtifSayings over 4 years
    Similar question is already answered. stackoverflow.com/questions/10863572/…
  • Alberto M
    Alberto M about 4 years
    the answer is now deprecated, you should use getSupportFragmentManager().popBackStack()
  • Ayxan Haqverdili
    Ayxan Haqverdili almost 4 years
    requireActivity().onBackPressed() for Kotlin
  • John Glen
    John Glen over 3 years
    This sends me back to the first fragment.
  • acmpo6ou
    acmpo6ou over 3 years
    in kotlin you should use supportFragmentManager().popBackStack()
  • Kraigolas
    Kraigolas over 3 years
    Note 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
    karan_for_you over 3 years
    This method comes in handy when you are using a custom designed toolbar. Works like a charm.
  • Andy Weinstein
    Andy Weinstein over 3 years
    If 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.