Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking back button after a Fragment transaction using addToBackStack does nothing

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?

like image 200
jul Avatar asked Aug 19 '13 02:08

jul


1 Answers

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!

like image 175
Abel Paz Avatar answered Sep 20 '22 10:09

Abel Paz