Clicking back button after a Fragment transaction using addToBackStack does nothing

jul picture jul · Aug 19, 2013 · Viewed 20.8k times · Source

I want to be able to reverse a replace FragmentTransaction by using addToBackStack():

FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();         
Fragment scheduleFragment = new ScheduleFragment();     
fragmentTransaction.replace(R.id.content_container, scheduleFragment, "scheduleFragment");
fragmentTransaction.addToBackStack("scheduleFragment");
fragmentTransaction.commit();

but after that, clicking the back button does nothing.

From the doc and it's supposed to reverse the transaction.

What am I missing?

Answer

Abel Paz picture Abel Paz · Dec 18, 2013

The right way to do this is using onBackPressed() method to catch that back event in your app, and then "pop" the backStack with popBackStack(). For example:

public void onBackPressed()
{
    // Catch back action and pops from backstack
    // (if you called previously to addToBackStack() in your transaction)
    if (getSupportFragmentManager().getBackStackEntryCount() > 0){
        getSupportFragmentManager().popBackStack();
    }
    // Default action on back pressed
    else super.onBackPressed();
}

PD: Sorry for the delay answering, but I just saw your question. Hope it helps!