Android Toolbar.inflateMenu 似乎什么都不做
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26511981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Toolbar.inflateMenu seems to do nothing
提问by danijoo
Im currently messing arround with the new AppCompat library bringing material design to older devices.
我目前正在使用新的 AppCompat 库,为旧设备带来材料设计。
Setting a toolbar as actionbar works fine for me, but the toolbar seems to not do anything on calling inflateMenu(int resId)
. From the docs, i thought this is to replace getMenuInflater().inflate(int resId)
called from onCreateOptionsMenu.
If I do the latter, the menu items are correctly inflated and added to the toolbar, but inflateMenu seems to to nothing.
将工具栏设置为操作栏对我来说很好用,但工具栏似乎在调用inflateMenu(int resId)
. 从文档中,我认为这是替换getMenuInflater().inflate(int resId)
从 onCreateOptionsMenu 调用的。如果我做后者,菜单项会正确膨胀并添加到工具栏,但 inflateMenu 似乎没有。
What am I missing?
我错过了什么?
Activity Code:
活动代码:
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.main); // this does nothing at all
setSupportActionBar(toolbar);
}
// this works
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Thanks in advance!
提前致谢!
回答by MrEngineer13
If you are calling setSupportActionBar()
you don't need to use toolbar.inflateMenu()
because the Toolbar is acting as your ActionBar. All menu related callbacks are via the default ones. The only time you need to call toolbar.inflateMenu()
is when you are using the Toolbar as a standalone widget. In this case you will also have to handle menu item click events via
如果您正在调用 setSupportActionBar()
,则不需要使用,toolbar.inflateMenu()
因为 Toolbar 充当您的 ActionBar。所有与菜单相关的回调都是通过默认的。唯一需要调用的toolbar.inflateMenu()
是将工具栏用作独立小部件时。在这种情况下,您还必须通过以下方式处理菜单项单击事件
toolbar.setOnMenuItemClickListener(
new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// Handle menu item click event
return true;
}
});