1

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>

1 Answer 1

4

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I've followed a lot of SO answers, but none were mentioning the .setNavigationItemSelectedListener(this) part, which fixed my even listener. You're the saviour of today!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.