Kotlin中的方法应返回布尔值
当我按下我称之为“主页”的导航项时,我想显示主页屏幕。我不能这样做,因为该方法应该返回一个布尔类型Kotlin中的方法应返回布尔值,kotlin,Kotlin,当我按下我称之为“主页”的导航项时,我想显示主页屏幕。我不能这样做,因为该方法应该返回一个布尔类型 override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.nav_home -> // I want to display the home screen here else -> return sup
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.nav_home ->
// I want to display the home screen here
else ->
return super.onOptionsItemSelected(item)
}
}
您可以将此行
return super.onoptions itemselected(item)
放在when
block:override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.nav_home ->
// your code here
}
return super.onOptionsItemSelected(item)
}
确保在when
块中包含所有菜单项这样,您就可以从该方法返回一个
布尔值
在您的问题中,您提到了导航项,因此如果您谈论的是导航抽屉,您应该实现onNavigationItemSelected()
,而不是onOptions ItemSelected()
在Kotlin中,when
语句将从所选语句返回值
return when (item.itemId) {
R.id.nav_home ->
// your code
return true
else ->
return super.onOptionsItemSelected(item)
}
伟大的阿里乌·艾哈迈德。请接受这个答案,如果它适合你。
return when (item.itemId) {
R.id.nav_home ->
// your code
return true
else ->
return super.onOptionsItemSelected(item)
}