我正在创建一个带有Navigationview的可折叠工具栏,它可以正常工作,但是当我选择菜单项时,使用 onOptionsItemSelected 做Toast时,没有Toast。 / p>
谁能帮我知道怎么了?
这是我的MainActivity
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
main_nav_view.setNavigationItemSelectedListener(this)
//set navigation view
val toggle = ActionBarDrawerToggle(
this, main_drawer_layout, main_toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
main_drawer_layout.addDrawerListener(toggle)
toggle.syncState()
}
override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
// set item as selected to persist highlight
menuItem.isChecked = true
closeDrawer()
return true
}
// close drawer when item is tapped
private fun closeDrawer() {
main_drawer_layout.closeDrawer(Gravity.START)
}
override fun onBackPressed() {
if (main_drawer_layout.isDrawerOpen(GravityCompat.START)) {
closeDrawer()
} else {
super.onBackPressed()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle presses on the action bar menu items
when (item.itemId) {
R.id.item1 -> {
Toast.makeText(this, "Item 1 pressed", Toast.LENGTH_LONG).show()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
答案 0 :(得分:0)
上下文应为“ MainActivity.this”而不是“ this”,因为它位于回调方法内部。
如果在Toast行上设置断点会怎样?到达断点了吗?
答案 1 :(得分:0)
您必须创建一个新功能,因为它与选定的导航冲突。您可以创建一个名为initNavigationDrawer()的函数,然后在oncreate中调用它。
答案 2 :(得分:0)