4

I just started using Android NavigationUI to implement Fragment Navigation through a drawer menu. While it does feel a bit like magic, I have one main issue with it. That is, I have a logout item in the menu that should not Navigate to any Fragment, but rather to an "action". While I found similar questions here such as this one, I haven't found a clear answer to my question yet. The following is the function I'm currently using to setup the navigation:

private fun setupNav() {
    val binding: ActivityMainMenuBinding = DataBindingUtil.setContentView(this,
            R.layout.activity_main_menu)
    drawerLayout = binding.drawerLayout
    navController = Navigation.findNavController(this, R.id.content_frame)
    appBarConfiguration = AppBarConfiguration(navController.graph, drawerLayout)

    // Set up ActionBar
    setSupportActionBar(binding.toolbar)
    setupActionBarWithNavController(navController, appBarConfiguration)
    binding.navView.setupWithNavController(navController)
}

If you have any suggestions on how I could approach this, it would be truly appreciated if you could share them.

Giulio Colleluori
  • 1,261
  • 2
  • 10
  • 16

1 Answers1

3

You just need to add below mentioned code

    nav_view.menu.findItem(R.id.nav_logout).setOnMenuItemClickListener {
            Log.e("=>"," You clicked on logout !!! ")
            true
        }

and Here is my full code

    class NavigationDrawerActivity : AppCompatActivity() {

    private lateinit var appBarConfig: AppBarConfiguration

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_navigation_drawer)
        setSupportActionBar(toolbar)

        val navController: NavController = findNavController(R.id.nav_host_fragment)

        appBarConfig = AppBarConfiguration(
            setOf(
                R.id.nav_home,
                R.id.nav_gallery,
                R.id.nav_slideshow,
                R.id.nav_tools,
                R.id.nav_share,
                R.id.nav_send
            )
            , drawer_layout
        )

        setupActionBarWithNavController(navController, appBarConfig)
        nav_view.setupWithNavController(navController)

        //For log out button related stuff
        nav_view.menu.findItem(R.id.nav_logout).setOnMenuItemClickListener {
            Log.e("=>"," You clicked on logout !!! ")
            true
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        return findNavController(R.id.nav_host_fragment).navigateUp(appBarConfig)
                || super.onSupportNavigateUp()
    }
}

You can also check out my project from Git Hub by this this link

Mohd Sakib Syed
  • 1,679
  • 1
  • 25
  • 42