Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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??????????

like image 210
scottysseus Avatar asked May 19 '14 00:05

scottysseus


People also ask

What is addToBackStack null?

Use . addToBackStack(null) : If you don't want later pop more than one back stack, but still want to pop one at a time.

How do you ensure that the user can return to the previous fragment by pressing the back button?

Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.


1 Answers

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();
    }
}
like image 70
Bobbake4 Avatar answered Sep 20 '22 05:09

Bobbake4