Android Jetpack导航-带抽屉项的自定义操作

问题描述:

我正在使用新的 Jetpack Android导航与抽屉布局"结合使用.当在Drawer XML中使用相同的ID并与Navigation Graph中的Fragments一起使用时,一切都按预期进行.我设置了所有内容:

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 the following menu and would like to logout the user when clicked "Logout":

我找到了解决方案:

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