如何在 android kotlin 中的导航项抽屉上添加点击事件?

How to add click event on navigation item drawer in android kotlin?

我想在单击导航抽屉中的某个项目时添加单击事件,我使用了 onNavigationItemSelected 方法但它不起作用,有帮助吗?

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>

由于您覆盖了 onNavigationItemSelected,我想您已将 NavigationView.OnNavigationItemSelectedListener 直接实现到您的 activity/fragment。

确保在创建时将其添加到导航中

navigation_view.setNavigationItemSelectedListener(this)

或者其他选择是将其直接实现到您的导航而不是 activity/fragment。删除您发布的代码和 activity/fragment 实现并像这样使用 kotlin lambdas

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
}