Reputation: 714
I am trying to implement jetpack navigation on my android app. I have created a navigational graph as shown below:
and navigational drawer menu xml as shown below:
according to the documentation in the android developer site, here
giving the menu items the same id as the fragments or destinations should be enough to ensure that clicking on an menu item will navigate me to the specified fragment. This doesn't seem to work, am I missing something?
Upvotes: 3
Views: 4476
Reputation: 51
@Dracarys You should use
implementation "android.arch.navigation:navigation-ui-ktx:1.0.0-alpha04"
instead of
implementation "android.arch.navigation:navigation-ui:1.0.0-alpha04"
pay attention to -ktx part in case if you are using Kotlin. Then you will see navigationView.setupWithNavController(navController)
method
[UPD 1]
Also, I faced with same issue, when I get navController by calling findNavController(view)
. Try to use findNavController(activity, id)
and pass it to setupWithNavController(navController)
method. It works for me now
Upvotes: 4
Reputation: 11752
I think standard custom solution is better, as you can handle different menu items with Navigation graph or yourself (like Sign out item)
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.navSignOut -> {
loginViewModel.logout()
}
else -> {
val navController = findNavController(R.id.main_nav_host_fragment)
navController.navigate(item.itemId)
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
Upvotes: 1
Reputation: 11
To use NavigationUI#setupWithNavController() you need:
implementation 'android.arch.navigation:navigation-ui:1.0.0-alpha02'
Upvotes: 1
Reputation: 714
This is the piece of code I added to my one of my fragment's onCreate to make it work. I had initially tried doing this on my MainActivity with no success.
val navigationView = activity?.findViewById<NavigationView>(R.id.nav_view)
val navController = findNavController(this)
navigationView?.let { NavigationUI.setupWithNavController(it, navController) }
Upvotes: 0
Reputation: 11995
According to the docs, there's a piece of code wiring you need to do:
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
NavigationUI.setupWithNavController(navigationView, navController);
or in kotlin:
val navigationView = findViewById(R.id.nav_view)
navigationView.setupWithNavController(navController)
Upvotes: 3