Programmatically go back to the previous fragment in the backstack

Aske B. picture Aske B. · Jun 2, 2012 · Viewed 280.2k times · Source

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?

Answer

stuckless picture stuckless · Jun 2, 2012

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

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