Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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":

like image 563
Paul Spiesberger Avatar asked Oct 08 '18 10:10

Paul Spiesberger


1 Answers

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
}
like image 116
Paul Spiesberger Avatar answered Nov 11 '22 20:11

Paul Spiesberger