Home > Back-end >  How to add click event on navigation item drawer in android kotlin?
How to add click event on navigation item drawer in android kotlin?

Time:11-22

I want to add click event when I click on one of the item in navigation drawer, I have used onNavigationItemSelected method but it's not working, Any help?

override fun onNavigationItemSelected(item: MenuItem): Boolean {
        TODO("Not yet implemented")
        val id = item.itemId


        if (id == R.id.nav_signout) {
            Toast.makeText(this, "Sign out",  Toast.LENGTH_SHORT).show()
        }

        return true
    }

drawer.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">
    <group android:checkableBehavior="single">
      <item android:title="Authentication">
         <menu android:checkableBehavior="all">
                <item
                    android:id="@ id/nav_signout"
                    android:icon="@drawable/ic_menu_gallery"
                    android:title="Sign out" />

            </menu>
      </item>
    </group>
</menu>

CodePudding user response:

Since you are overriding onNavigationItemSelected I suppose you implemented NavigationView.OnNavigationItemSelectedListener directly to your activity/fragment.

Make sure you added it to your navigation when it is created

navigation_view.setNavigationItemSelectedListener(this)

Or other option would be to implement it directly to your navigation instead of activity/fragment. Remove code you posted and activity/fragment implementation and use kotlin lambdas like this

navigation_view.setNavigationItemSelectedListener{
    TODO("Not yet implemented")
    val id = item.itemId


    if (id == R.id.nav_signout) {
        Toast.makeText(this, "Sign out",  Toast.LENGTH_SHORT).show()
    }

    return true
}
  • Related