I've got an issue concerning the implementation of a Drawer Layout with Navigation component.
I have created the drawer layout using the include Navigation Drawer Activity of Android Studio.
Actually, all is fine if the menu items purpose is to change fragments or activity (like programs, songs, settings etc ... on the screenshot) define in the navigation XML
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
val navView: NavigationView = findViewById(R.id.nav_view)
val navController = findNavController(R.id.nav_host_fragment)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = AppBarConfiguration(
setOf(
R.id.nav_user_programs_list,
R.id.nav_user_songs_list,
R.id.nav_user_settings,
R.id.nav_user_legal_notices,
R.id.nav_games
), drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
However, I also would like to execute a logout action on the "logout" menu item without launching another fragment or activity :
I managed to do it like that :
navView.setNavigationItemSelectedListener {
if (it.itemId == R.id.nav_logout) {
logoutUser()
}
true
}
But my problem is : With that method, all the other items which used to work (changing fragment) don't work anymore because it called the NavigationItemSelectedListener which do nothing in that case.
Is there a solution to combine the both method ? :
I hope it's clear enough. Don't hesitate if you need precisions.
Thank you very much.
Navigation drawers provide access to destinations and app functionality, such as switching accounts. They can either be permanently on-screen or controlled by a navigation menu icon. Navigation drawers are recommended for: Apps with five or more top-level destinations.
To use a DrawerLayout, position your primary content view as the first child with width and height of match_parent and no layout_gravity> . Add drawers as child views after the main content view and set the layout_gravity appropriately. Drawers commonly use match_parent for height with a fixed width.
Ok, I figured it out, this is what the framework is calling for you:
NavigationUI.onNavDestinationSelected(dest, navController)
So you can do the same for all other cases:
navView.setNavigationItemSelectedListener {dest ->
when(dest.itemId) {
R.id.logout -> logout()
else -> NavigationUI.onNavDestinationSelected(dest, navController)
}
true
}
The above stops "automatically closing" the drawer, so..
navView.setNavigationItemSelectedListener {dest ->
when(dest.itemId) {
else -> {
NavigationUI.onNavDestinationSelected(dest, navController)
drawerLayout.closeDrawers()
}
}
true
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With