Back button closing app even when using FragmentTransaction.addToBackStack()

scottysseus picture scottysseus · May 19, 2014 · Viewed 12.9k times · Source

None of the other questions I have read on stackoverflow have been able to help with my problem. As far as I can tell, I am doing everything correctly.

I have a master/detail flow with fragments.

Upon creation of the main activity, the master fragment is loaded with the following code:

    Fragment frag;
    frag = new MainListFragment();//<-- **the master fragment**

    FragmentManager fm = getFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();
    transaction.replace(R.id.fragment_container, frag);
    Log.d("My Debug Bitches", "stack:" + fm.getBackStackEntryCount());
    transaction.commit();

The master fragment has a ListView; clicking on a list item brings up the details fragment like so:

@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
    super.onListItemClick(listView, view, position, id);


    FragmentManager fm = getFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();
    SubListFragment frag = new SubListFragment();//<-- **the detail fragment**

    transaction.replace(R.id.fragment_container, frag);
    transaction.addToBackStack(null);
    transaction.commit();
    fm.executePendingTransactions();
    Log.d("My Debug Bitches", "stack:" + fm.getBackStackEntryCount());

}

Now, according to LogCat, the BackStackEntryCount changes from 0 to 1 after I navigate from master fragment to detail fragment: enter image description here

So why is it that, when I click the back button while in the details fragment, that the app closes instead of returning to the master fragment??????????

Answer

Bobbake4 picture Bobbake4 · May 19, 2014

You have to add the popBackStack() call to the onBackPressed() method of the activity.

Ex:

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