Search code examples
androidnavigation-drawerdrawerlayouthamburger-menu

How does the Navigation Drawer Views Activity app open the drawer via the hamburger icon?


Android Studio ships with the sample app 'Navigation Drawer Views Activity', which can be created via the new app dialog. I've tried to follow the code in it to implement a navigation drawer in my app. Everything works, except that the drawer does not open or close with a tap on the hamburger icon.

Searching online, this answer (and others) point to ActionBarDrawerToggle. However, the sample app 'Navigation Drawer Views Activity' does not use ActionBarDrawerToggle. Thus, the question is, what is the key piece of code in said sample app that makes it open the navigation drawer with a tap on the hamburger icon?

Edit: I've noticed something interesting: in the sample app the hamburger icon stays the hamburger icon. In my app (now with ActionBarDrawerToggle) the hamburger icon becomes a back arrow when I navigate to another fragment. But when I tap it, my app doesn't navigate back to the previous fragment, but simply opens the drawer. I prefer the behaviour of the sample app. How can I achieve that?

Edit (again): my fragment provides a menu via requireActivity().addMenuProvider(...). That seems to have blocked the tap on the hamburger icon. Without the menu a tap on the hamburger icon opens the drawer without ActionBarDrawerToggle. So far so good. But the hamburger icon still changes into a back arrow when navigating to another fragment. Now however, a tap on the back arrow navigates back to the previous fragment, without opening the drawer.

This inconsistent behaviour is driving me crazy. How can I achieve the behaviour of the sample app (and still have a menu for my fragment)?


Solution

  • I initialized the AppBarConfiguration like this:

    appBarConfiguration = AppBarConfiguration(navController.graph, binding.drawerLayout)
    

    whereas in the sample app 'Navigation Drawer Views Activity' it is initialized like this:

        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow
            ), drawerLayout
        )
    

    The documentation explains the difference. For the former:

    The NavGraph whose start destination should be considered the only top level destination. The Up button will not be displayed when on the start destination of the graph.

    and the latter:

    The set of destinations by id considered at the top level of your information hierarchy. The Up button will not be displayed when on these destinations.

    Fun fact: AppBarConfiguration is not a constructor. It's a static method yielding an object of type AppBarConfiguration. Yep. I wonder if this is all just a big joke to Google...