我的菜单如下:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/settings"
android:icon="@drawable/ic_tune"
android:title="@string/menu_title_settings"
app:showAsAction="ifRoom" />
<item
android:id="@+id/add"
android:icon="@drawable/ic_plus"
android:title="@string/menu_title_add"
app:showAsAction="ifRoom" />
</menu>
我这样处理活动中的菜单:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_categories)
setupToolbar()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
MenuInflater(this).inflate(R.menu.categories_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.settings -> {
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show()
false
}
R.id.add -> {
Toast.makeText(this, "Add", Toast.LENGTH_SHORT).show()
false
}
else -> super.onContextItemSelected(item)
}
}
private fun setupToolbar() {
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = "title"
supportActionBar?.subtitle = "subtitle"
}
最终,我的菜单膨胀了,但是菜单项没有显示为动作(图标),而是隐藏在溢出菜单中。从工具栏中删除标题和副标题以腾出更多空间,并将app:showAsAction更改为“ always”始终对我没有任何帮助...