Search code examples
androidandroid-fragmentsbottomnavigationviewfragmentmanager

Android - prevent to open previous fragment


guys. This must be a silly question but i'm not managing to work this out. My scenario is: i have in my MainActivity a BottomNavigation which i navigate over three fragments. And my problem is that when the back button (from android bottom navigation toolbar) is pressed the previous fragment opens but i want the app to close. So my question is: how i manage to prevent the previous fragments to open?

PS: I know it has something to do with FragmentMananger back stack but i did not understand how to use it.

PS2: Sorry for bad english.


Solution

  • The fragments are on the backstack.

    Edit:

    Work with FragmentTransaction and use addToBackStack (null)

    //  Create new fragment and transaction
        Fragment newFragment = new  ExampleFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    
    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);
    
    // Commit the transaction
        transaction.commit();