Search code examples
androidback-buttonslidingdrawernavigation-drawer

Updating the Navigation Drawer (with DrawerLayout) when back button is pressed


I am designing an app on the Android with a Navigation Drawer. Lets say I navigate through fragments and go from Fragment 1 to Fragment 2. Everything works fine but when I am in Fragment 2 (which loads from the navigation drawer) and click the system back button althought I get the previous fragment (I use addToBackStack) the navigation drawer doesn't get updated and the cell of Fragment 2 is highlighted. What should I do to fix this?


Solution

  • Found the solution:

    Added a tag in every addToBackStack. So the code if I call addToBackStack it looks like this:

    addToBackStack("Fragment1");
    addToBackStack("Fragment2");
    

    whenever I put each fragment to the stack. Then I override the back button pressed:

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        FragmentManager fm = getSupportFragmentManager();
        String stackName = null;
        for(int entry = 0; entry < fm.getBackStackEntryCount(); entry++){
            stackName = fm.getBackStackEntryAt(entry).getName();
            Log.i("BC", "stackEntry" + entry);
        }
        if (stackName == "Fragment1"){
            mDrawerList.setItemChecked(0, true);
        } else if (stackName == "Fragment2") {
            mDrawerList.setItemChecked(1, true);
        }
    }