在Android MaterialToolbar中,通过设置app:menu属性,我们可以将一个菜单资源文件与一个Toolbar关联起来。例如:
在我们的布局文件中添加一个Toolbar,指定它的menu属性:
在此示例中,我们指定了一个名为my_menu的菜单资源文件,该菜单会出现在我们的Toolbar上。我们也可以在Activity或Fragment中声明和处理这个菜单。如下所示:
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.my_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_settings -> {
// Action to be performed when the "Settings" menu item is clicked
true
}
R.id.action_profile -> {
// Action to be performed when the "Profile" menu item is clicked
true
}
else -> super.onOptionsItemSelected(item)
}
}
在这个示例中,我们重写了onCreateOptionsMenu()方法来让系统来生成我们的菜单,并且响应用户的选项选择,重写了onOptionsItemSelected()方法。
这就是通过app:menu属性在Android MaterialToolbar中关联菜单资源的用法。