I have a navigation drawer with a navigation view with menu items and I'm using navigation component. How do I specify an argument for a destination at runtime when a certain menu item in the navigation view is clicked?
I know I can set default arguments in the nav graph but this is not what I want to do because the argument passed needs to be decided at runtime. For toolbar menu items, I have no issue as I'm able to override onOptionsItemSelected
. My issue is specifically with menu items in the navigation view.
I have tried the approach here: https://stackoverflow.com/a/54086631/10933532 but I am unable to create a NavArgument
as described. The NavArgument
class does not give me the public Builder()
constructor.
I set up my navigation view with the navigation controller in mainactivity onCreate like this:
NavigationUI.setupWithNavController(navigationView,navController);
I also do this to set up my toolbar with the navigation controller:
NavigationUI.setupWithNavController(collapsingToolbarLayout,toolbar,navController,appBarConfiguration);
Can someone please point me in the right direction?
You can use a custom NavigationItemSelectedListener
.
Pay attention because in this way you are removing the original listener. You have to call NavigationUI.onNavDestinationSelected()
to trigger the default behavior.
navigationView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.xxxxx -> {
// handle click
true
}
}
//Call the original listener
NavigationUI.onNavDestinationSelected(it, navController)
drawerLayout.closeDrawer(GravityCompat.START)
true
}