Doilio Matsinhe
Doilio Matsinhe

Reputation: 2280

How to configure DrawerLayout using Navigation Components

I have 2 fragments where I would like to use the hamburger icon to properly access the DrawerLayout.

HomeFragment and FavoritesFragment.

What happens is, when I click the hamburger icon, and select favorites menu item, it navigates to FavoritesFragment, but the hamburger icon becomes a back arrow.

I would like to show the hamburger icon on both fragments.

This is the what I have on my MainActivity:

    setupActionBarWithNavController(navController, drawerLayout)
    setupWithNavController(binding.navView, navController)

    navController.addOnDestinationChangedListener { controller, destination, _ ->
        when (destination.id) {
            R.id.categoryFragment -> drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
            R.id.favoritesFragment -> drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
            else -> drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
        }
    }

Home Fragment Favorites Fragment

Upvotes: 1

Views: 51

Answers (1)

Doilio Matsinhe
Doilio Matsinhe

Reputation: 2280

I ended Up finding the solution for this with a few lines of code: I'll leave commented out the parts of the code I've replaced.

Explanation

So the AppBarConfiguration() takes 2 parameters, topLevelDestinationIds and a drawerLayout, In this case I have 2 Top Level Destinations so I put them in a Set.

Instead of passing a drawerLayout to setupActionBarWithNavController, I passed in the new Appbar configuration.

Then I made onSupportNavigateUp aware that it was supposed to take the AppBarconfiguration into account.

     appBarConfiguration = AppBarConfiguration(
        setOf(
            R.id.categoryFragment,
            R.id.favoritesFragment
        ), drawerLayout
    )
    //setupActionBarWithNavController(navController, drawerLayout)
    setupActionBarWithNavController(navController, appBarConfiguration)

override fun onSupportNavigateUp(): Boolean {
    //return navigateUp(navController, drawerLayout)
    return navigateUp(navController, appBarConfiguration)
}

FavoritesFragment

Upvotes: 1

Related Questions