Search code examples
androidandroid-fragmentsfragment-backstack

Android: Back stack doesnt work properly


I am making an app with a couple of screens and it has to be possible to navigate through the app with the back button.

I am having trouble with one screen, my MainFragment. It doesn't seem recognise the backstack.

The MainFragment is started from the MainActivity here:

if (savedInstanceState == null) {
        getFragmentManager().beginTransaction().replace(R.id.container, new MainFragment()).addToBackStack("mainFragment")
                .commit();
    }

So when the app starts, this fragment is loaded. From this mainFragment I can navigate to different screens. I have methods in my mainActivity which I call in my MainFragment to navigate:

public void navigateToListCountriesSeen(){
    getFragmentManager().beginTransaction().replace(R.id.container, new listCountriesSeenFragment()).addToBackStack("listSeen")
            .commit();
}

public void navigateToListCountriesToSee(){
    getFragmentManager().beginTransaction().replace(R.id.container, new listCountriesToSeeFragment()).addToBackStack("listToSee")
            .commit();
}

But whenever I am in the countriesSeen or CountriesToSee fragments/screens and I press the back button, the app just closes...

How do I solve that?


Solution

  • Use addToBackStack() if you want the navigation to backup on the backspace key. Here's an example:

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    ListCountriesSeenFragment listCountriesSeenFragment = new ListCountriesSeenFragment();
    fragmentTransaction.replace(R.id.frameLayout, listCountriesSeenFragment, FRAGMENT_TAG_COUNTRIES_SEEN);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();