Why the addToBackStack does not work when back button pressed

1.2k Views Asked by At

I was confused by it.

I hava a activity A, Fragment F1 and F2, when one button was clicked, I want to hide F1 and add the F2 to the same place and can go back to F1 by back button. So I did as below.

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.hide(getFragmentManager().findFragmentByTag(CHAT_LIST_FRAGMENT_TAG));
    transaction.add(R.id.content_frame, MessageListFragment.newInstance(username, false));
    transaction.addToBackStack(null);
    transaction.commit();

But when I pressed the back button, the activity finished instead of back to the F1. I tried to use replace, and the result is same.

Does the only solution is to override the onBackPress method?


More

I tried the code like below.

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.repalce(R.id.content_frame, MessageListFragment.newInstance(username, false));
    transaction.addToBackStack(null);
    transaction.commit();

But nothing changed.

2

There are 2 best solutions below

2
On

Try to use replace() instead of hide() + add(). Here is corresponding Android documentation.

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, MessageListFragment.newInstance(username, false));
transaction.addToBackStack(null);
transaction.commit();
1
On
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.container, fragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commitAllowingStateLoss();

This works. Probably, you need "getSupportFragmentManager" instead of yours getFragmentManager

NB! don't "addToBackStack" the root fragment, otherwise, it would end up with blank screen, when you click back, in attempt to close the app.