Toolbar.inflateMenu 似乎什么都不做 [英] Toolbar.inflateMenu seems to do nothing

查看:82
本文介绍了Toolbar.inflateMenu 似乎什么都不做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用新的 AppCompat 库,为旧设备带来 Material Design.

Im currently messing arround with the new AppCompat library bringing material design to older devices.

将工具栏设置为操作栏对我来说很好用,但工具栏似乎在调用 inflateMenu(int resId) 时没有做任何事情.从文档中,我认为这是替换从 onCreateOptionsMenu 调用的 getMenuInflater().inflate(int resId) .如果我做后者,菜单项会正确膨胀并添加到工具栏,但 inflateMenu 似乎没有.

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.

我错过了什么?

活动代码:

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;
}

提前致谢!

推荐答案

如果你正在调用 setSupportActionBar() 你不需要使用 toolbar.inflateMenu()因为 Toolbar 充当您的 ActionBar.所有与菜单相关的回调都是通过默认的.唯一需要调用 toolbar.inflateMenu() 的时间是将工具栏用作独立小部件时.在这种情况下,您还必须通过

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

toolbar.setOnMenuItemClickListener(
        new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                // Handle menu item click event
                return true;
            }
});

这篇关于Toolbar.inflateMenu 似乎什么都不做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆