61

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

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.

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!

MrEngineer13
  • 38,642
  • 13
  • 74
  • 93
danijoo
  • 2,823
  • 4
  • 23
  • 43

1 Answers1

110

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;
            }
});
MrEngineer13
  • 38,642
  • 13
  • 74
  • 93
  • 11
    Thanks for the clarification. So inflateMenu seems to be only relevant/working for toolbars that are not set as ActionBar. – danijoo Oct 22 '14 at 21:27
  • In a standard (non-standalone widget) I am seeing that onCreateOptionsMenu is not called until *after* onResume!!! This breaks my current technique of using onCreateOptionsMenu to populate member fields of custom views in the toolbar before onResume is called. Any idea what is going wrong or how to do this? – swooby Feb 21 '15 at 00:20
  • 3
    I am using `setSupportActionBar`. How do I show action items on the toolbar if I'm not inflating the menu?? – IgorGanapolsky May 20 '15 at 20:58
  • 1
    If you really want to use toolbar.inflateMenu(), you can follow this answer: https://stackoverflow.com/a/63529156/2534007 – Mohib Irshad Aug 21 '20 at 19:46