Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addToBackStack doesn't work, closes the activity instead of popping back fragments

I have a probleam and I can't find a solution anywhere.

My app doesn't return to previous fragment when I press the back button, instead closes the activity.

I have an activity that displays 4 fragment: [1],[2],[3],[4]. I can switch between the first 3 fragments with the action bar, I don't want to add them to the back stack.

Fragment [4] is a detailed view of an item selected in fragment [3]. When I press back in [4] I want to return to fragment [3], not closing the app.

The transitions are done in this way BY THE ACTIVITY in which fragments are placed:

private void replaceFragment(Fragment fragment, boolean toBackStack){

    if(fragment != null){

        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.container, fragment);

        if(toBackStack)
            fragmentTransaction.addToBackStack(null);

        fragmentTransaction.commit();
    }
}

where toBackStack is always false except when the transition is from [3] to [4].

If I pass toBackStack true in every transition, the activity closes anyway.

like image 237
JoP Avatar asked May 15 '13 09:05

JoP


1 Answers

I had the same problem. Specifically, I am implementing a PreferenceFragment and I want the back button to return me to whatever the previously loaded fragment was.

It appears that the "back stack" is something that is not automatically triggered with the system back button. My solution was to manually pop the back stack from the onBackPressed override:

@Override
public void onBackPressed()
{
    if (inSettings)
    {
        backFromSettingsFragment();
        return;
    }
    super.onBackPressed();
}

Whenever I navigate to my preferences fragment, I set the inSettings boolean to true in the activity to retain that state. Here is what my backFromSettingsFragment method looks like:

private void backFromSettingsFragment()
{
    inSettings = false;
    getFragmentManager().popBackStack();
}

So, if you are able to track the state of when you are in Fragment [4] and intercept the back button, you should be able to manually call

getFragmentManager().popBackStack();

to go back to Fragment [3].

Note: remember that you need to add Fragment [3] to the back stack, not Fragment[4]. (Unless [4] goes to [5] and you need to back to [4] as well.)

like image 78
kdenney Avatar answered Sep 29 '22 14:09

kdenney