How to Have Navigation Drawer setup with Navigation Controller and handle individual Menu Items

余生颓废 提交于 2019-12-19 10:19:12

问题


I would like to have most of menu item handled by Navigation Component's controller, but I also want to handle one "Log out" menu item individually like this:

val navController = findNavController(R.id.nav_host_fragment)
        nav_view.setNavigationItemSelectedListener { item ->
            when(item.itemId) {
                R.id.logout_menu_item -> {
                    Toast.makeText(context, "Logut Menu Item Touched", Toast.LENGTH_LONG).show()
                    true
                }
                else -> false
            }
        }
        nav_view.setupWithNavController(navController)
        bottom_navigation.setupWithNavController(navController)

Why this doesn't work, and how to resolve this issue?


回答1:


I'm not sure that there is a proper way to do this at the moment, but you could always just not use the setupWithNavController method.

I ran into this as well and, as a test, moved my call to setNavigationItemSelectedListener to after the call to setupWithNavController and and my navigation code for signing out was running but the rest of the navigation was not. I take this to mean that the navigationListener is overwritten on subsequent calls to setNavigationItemSelectedListener and that setupWithNavController calls setNavigationItemSelectedListener internally.

I attempted to verify this in google source, but couldn't find the repo easily.

I worked around the problem by not calling setupWithNavController and instead doing something like:

    navigationDrawer?.setNavigationItemSelectedListener { menuItem ->
        if (menuItem.itemId == R.id.action_sign_out) {
            // sign out logic
            return@setNavigationItemSelectedListener true
        }

        val result = menuItem.onNavDestinationSelected(navigationController)
        drawerLayout?.closeDrawers()
        result
    }


来源:https://stackoverflow.com/questions/51743692/how-to-have-navigation-drawer-setup-with-navigation-controller-and-handle-indivi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!