1

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.

Fadi Obaji
  • 1,454
  • 4
  • 27
  • 57

1 Answers1

1

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.

Ashton Engberg
  • 5,949
  • 2
  • 19
  • 14
  • I'm have the same trouble. What is the `updateCurrentSelectedItemBackground()` I can't find it. – priyank Apr 26 '15 at 15:32
  • You have to make this as part of your code in response to the user clicking on an item in the list: if you posted your code, I would offer an example, but I am not going to code up an entire thing (since I don't use nav drawers) just to make this point. I'll edit for clarity... – Ashton Engberg Apr 29 '15 at 23:11
  • Is it a good practice to change the NavigationView item in onResume() or onStart() in each Fragment? (Not only for selecting the item in the Nav, but also for changing the Toolbar title, for example). I want to do something similar to what @AshtonEngberg suggested, so it's the Fragment itself which says "Hey, I'm currently on screen". But I don't know if it is good or bad. – Kashmir Oct 15 '15 at 11:49
  • 1
    No. Fragments shouldn't directly mutate the Navigation Drawer/View. This is because fragments and the navigation drawer are both "children" of the parent activity: you should update the navigation drawer when swapping the fragments in your activity. Let the fragments do what they are responsible for, and nothing more. If some event in the fragment should effect the navigation view, it should do through via the activity for example through a callback interface (as exemplified by google dev docs on activity-fragment communication). – Ashton Engberg Oct 15 '15 at 18:46