Search code examples
androidandroid-fragmentsnavigation-drawernavigationitem

Android: How to change the selected item in Navigation Drawer onBackPressed()?


I implemented a NavigationDrawer and when i press on a NavigationDrawer item a Fragment Transaction happens and the item's background changes to indicate that it's selected. Now when i press the Hardware Back Button to go to the previous Fragment the Navigation Drawer item's background remains. How can i change the selected item to refer to the current Fragment when `onBackPressed' occur ?

Thanks in advance.


Solution

  • In your activity, override public void onBackPressed().

    Give each fragment that comes into view a number that (conveniently) corresponds to the position in the navigation drawer item. Or save the last fragment's position. Then when onBackPressed() is fired, either from the fragment's "position" or "id" or "tag" you associated with its nav item row, you can use this to correctly colorize the now current nav item (its easy to just reset them all to default, and recolor in the "current" fragment). That's what I meant by the method: updateCurrentSelectedItemBackground() which resets the backgrounds, selecting the correct background for the current item and setting the rest to their default background.

    Make sure to call super.onBackPressed() after you are done from within onBackPressed() so the system does it normal on back pressed behavior.