Toolbar.inflateMenu似乎无能为力无能为力、Toolbar、inflateMenu

2023-09-08 09:19:59 作者:心碎,誰來买單

即时通讯目前与新的应用程序兼容性库带来的材料设计,旧设备搞乱以防万一。

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

设置工具栏的动作条为我工作得很好,但在工具栏似乎在呼吁不做任何 inflateMenu(INT渣油)。从文档,我认为这是替代 getMenuInflater()。膨胀(INT渣油)的onCreateOptionsMenu名为。如果我做了后者,菜单项正确充气,并添加到工具栏,但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.

我是什么失踪?

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

在此先感谢!

推荐答案

如果您正在呼叫 setSupportActionBar()你不需要使用 toolbar.inflateMenu(),因为工具栏是作为你的动作条。所有菜单相关的回调是通过默认的。你需要调用的唯一时间 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;
            }
});