Programmatically go back to the previous fragment in the backstack

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?

  • What happens to running AsyncTasks when the Activity changes?
  • Select multiple contacts from phone book in android
  • Android Studio 2.2 : I keep seeing “GPU tools not installed, install now”
  • Store a List or Set in SharedPreferences
  • How to enable USB debugging in Android?
  • AllArgsConstructor from lombok is not found by Android Studio
  • 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?

  • Click on not fully visible imageButton with Espresso
  • How to know my Android application has been upgraded in order to reset an alarm?
  • Remove all debug logging calls before publishing: are there tools to do this?
  • Android XML Percent Symbol
  • whereNear query doesn't seem to work properly in Parse
  • Using AppCompat 'layout_behavior' with '@string/appbar_scrolling_view_behavior' throws exception
  • 6 Solutions collect form web for “Programmatically go back to the previous fragment in the backstack”

    Look at the getFragmentManager().popBackStack() methods (there are several to choose from)

    http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()

    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();  
        }
    }
    

    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.

    replace() does 2 things:

    1. Remove currently added fragment (A) from the container (C) you indicated
    2. Add new fragment (B) to the same container

    These 2 operations are what is saved as a Backstack record / transaction. Note that fragment A remains in created state, and its view is destroyed.

    Now popBackStack() reverses your last transaction that you’ve added to BackStack.

    In this case that would be 2 steps:

    1. Remove B from C
    2. Add A to C

    After this, fragment B becomes detached, and if you did not keep references to it, it will be garbage collected.

    To answer first part of your question, there’s no onCreate() call, because FragmentB remained in created state. And answer to second part of the question is a bit longer.

    First, it is important to understand that you don’t actually add Fragments to Backstack, you add FragmentTransactions. So when you think that you “replace with Fragment B, adding Fragment A to the back stack”, you actually add this whole operation to backstack – that is replacement of A with B. This replacement consists of 2 actions – remove A and add B.

    Then, next step is popping of the transaction that contains this replacement. So you’re not popping FragmentA, you’re reversing “remove A, add B”, which reversed is “remove B, add A”.

    And then final step should be clearer – there’s no B that FragmentManager is aware of, so when you add it by replacing A with B at your last step, B needs to go through its early lifecycle methods – onAttach() and onCreate().

    Code below illustrates what is happening.

    FragmentManager fm  = getFragmentManager();
    FragmentA fragmentA = new FragmentA();
    FragmentB fragmentB = new FragmentB();
    
    // 1. Show A
    fm.beginTransaction()
      .add(fragmentA, R.id.container)
      .commit();
    
    // 2. Replace A with B
    // FragmentManager keeps reference to fragmentA;
    // it stays attached and created; fragmentB goes 
    // through lifecycle methods onAttach(), onCreate()
    // and so on.
    fm.beginTransaction()
      .replace(fragmentB, R.id.container)
      .addToBackstack(null)
      .commit();
    
    // 2'. Alternative to replace() method
    fm.beginTransaction()
      .remove(fragmentA)
      .add(fragmentB, R.id.container)
      .addToBackstack(null)
      .commit();
    
    // 3. Reverse (2); Result - A is visible
    // What happens:
    //   1) fragmentB is removed from container, it is detached now;
    //      FragmentManager doesn't keep reference to it anymore
    //   2) Instance of FragmentA is placed back in the container
    // Now your Backstack is empty, FragmentManager is aware only
    // of FragmentA instance
    fm.popBackStack();
    
    // 4. Show B
    // Since fragmentB was detached, it goes through its early
    // lifecycle methods: onAttach() and onCreate().
    fm.beginTransaction()
      .replace(fragmentB, R.id.container)
      .addToBackstack(null)
      .commit();
    

    Add those line to your onBackPressed() Method. popBackStackImmediate() method will get you back to the previous fragment if you have any fragment on back stack
    `

    if(getFragmentManager().getBackStackEntryCount() > 0){
         getFragmentManager().popBackStackImmediate();
    }
    else{
        super.onBackPressed();
    }
    

    `

    Programmatically go back to the previous fragment using following code.

    if ( getFragmentManager().getBackStackEntryCount() > 0) 
    {
              getFragmentManager().popBackStack();
              return;
    }
    super.onBackPressed();
    
    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.