Android Kotlin 如何为导航抽屉(Navigation Drawer)菜单项添加点击事件
问题原因
onNavigationItemSelected方法首行的TODO("Not yet implemented")是导致逻辑不生效的核心问题:Kotlin标准库中的TODO()函数默认会主动抛出NotImplementedError异常,代码执行到这一行就会直接终止,后续的菜单ID判断、Toast弹窗逻辑完全不会被执行。
修复方案
- 首先删除
onNavigationItemSelected方法首行的TODO语句 - 确认Activity已经实现
NavigationView.OnNavigationItemSelectedListener接口 - 确认在
onCreate生命周期中已经给NavigationView绑定了监听器,示例如下:
// 替换为你布局文件中NavigationView对应的实际ID val navigationView = findViewById<NavigationView>(R.id.nav_view) navigationView.setNavigationItemSelectedListener(this)
修复后的完整点击事件代码示例:
override fun onNavigationItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == R.id.nav_signout) { Toast.makeText(this, "Sign out", Toast.LENGTH_SHORT).show() } // 可选:点击菜单项后自动关闭抽屉 // 替换为你布局中DrawerLayout对应的实际ID val drawerLayout = findViewById<DrawerLayout>(R.id.drawer_layout) drawerLayout.closeDrawer(GravityCompat.START) return true }
内容的提问来源于stack exchange,提问作者Nadish
相关产品推荐
相关产品推荐

