Android : Return to previous fragment on back press

Harsh picture Harsh · Aug 17, 2014 · Viewed 41.8k times · Source

I have implemented Navigation Drawer which is a subclass of Activity. I have many fragments in my application. My question goes here

Imagine there are 3 fragments :

Fragment_1 : Fragment_2 : Fragment_3

When I start my application, Fragment_1 is loaded When I click on some components on Fragment_1, I'm navigated to Fragment_2 and so on..

So it's like

Fragment_1 > Fragment_2 > Fragment_3

When I press back key from Fragment_2, I'm navigated back to Fragment_1 But when I press back key from Fragment_3, I'm navigated back to Fragment_1 (instead of Fragment_2)

I want something like this in my application on Back Key press

Fragment_1 < Fragment_2 < Fragment_3

I have used Fragment, FragmentManager, FragmentTransaction as follows :

MyFragment fragment = new MyFragment();
FragmentManager fragmentManager = getFragmentManager();

fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null)commit();

and I tried overriding onBackPressed() in my MainActivity :

@Override
public void onBackPressed() {


        getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        int count = getFragmentManager().getBackStackEntryCount();
        if (count == 0)
               super.onBackPressed();
    }

Answer

Leandro picture Leandro · Aug 17, 2014

Update your Activity#onBackPressed() method to:

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 0) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

The reason your implementation doesn't work is because the method FragmentManager#popBackStack() is asynchronous and does not happen right after it is called.

From the documentation:

This function is asynchronous -- it enqueues the request to pop, but the action will not be performed until the application returns to its event loop.

Reference: http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack(java.lang.String,%20int)