Search code examples
androidnavigation-drawerandroid-jetpackandroid-architecture-navigation

Android Jetpack Navigation - Custom Action with Drawer Item


I am using the new Jetpack Android Navigation in combination with a Drawer Layout. Everything is working as expected when using the same IDs in the Drawer XML in combination with Fragments in the Navigation Graph. I set everything up with:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val navController = findNavController(R.id.navigation_host_fragment)
        setupActionBarWithNavController(navController, find(R.id.drawer_layout))
        val navigationView = findViewById<NavigationView>(R.id.nav_view)
        navigationView.setupWithNavController(findNavController(R.id.navigation_host_fragment))
}

I would now like to also trigger custom action/code and not do a fragment transaction when clicking an item in my Drawer-Menu. I have a menu and would like to logout the user when clicked "Logout":


Solution

  • I found a solution:

    val navigationView = findViewById<NavigationView>(R.id.nav_view)
    val logoutItem = navigationView.menu.findItem(R.id.nav_logout)
    logoutItem.setOnMenuItemClickListener {
         toast("Log me out")
         true
    }