Navigation drawer, handling the back button to go to previous fragments?

后端 未结 6 1667
陌清茗
陌清茗 2020-12-02 14:45

I\'m using the built-in navigation drawer to run my app. I can\'t quite figure out how to handle the back button. When it\'s pressed I want it to load the very first fragmen

6条回答
  •  抹茶落季
    2020-12-02 14:56

    I would suggest avoiding an override of onBackPressed() altogether by managing your transactions properly in the first place. This will help to avoid having to implement crazy logic down the road.

    To do this first we need to set a private class variable in that will enable initialization:

    private boolean popNext = false;
    

    The following code allows us to setup the initial back function by placing it on the stack. Every time thereafter, when popNext is set to true, we pop the initial transaction and push the new one. So we are replacing the 1>X transaction with the 1>Y transaction.

    The extra embedded if statements deal with selecting the initial item, since we don't want to go from 1>1. If it's our initial case we just close the drawer. The other case needs to act like the back button, but we need to remember to set it as if it is returning to the initial state!

    if(popNext){
        if(i == INITIAL_POSITION){
            onBackPressed();
            mDrawerLayout.closeDrawer(mDrawerList);
            popNext = false;
            return;
        }
        getFragmentManager().popBackStackImmediate();
    }
    else{
        if(i == INITIAL_POSITION){
            mDrawerLayout.closeDrawer(mDrawerList);
            return;
        }
        popNext=true;
    }
    getFragmentManager()
    .beginTransaction()
    .replace(R.id.fragment_container, fragment)
    .addToBackStack(null)
    .commit();
    

    Note: My code uses getFragmentManager() instead of getSupportFragmentManager() which is a native function, I believe as of Honeycomb.

提交回复
热议问题