How to create a Menu instance programmatically? i.e. inflate a Menu outside onCreateOptionsMenu

iTech picture iTech · Jan 2, 2013 · Viewed 24.1k times · Source

I want to inflate a menu object outside onCreateOptionsMenu method (which means to create/show the menu when the user doesn't press the button), so I need to create a menu instance to pass it to the inflate method.

Here is an example of what I am trying to achieve:

Menu menu = // How to create an instance !? 
new MenuInflater(context).inflate(R.menu.my_menu, menu)

Menu is an interface, so I need to know which class is implementing it. I did browse Android code to get any hint on how a Menu object is created, but still could not find what I am looking for.

Edit 1

My goal is to fire an onOptionsItemSelected(MenuItem item) event from a custom view, which will be handled by the activity, so I need to have a MenuItem object with specific itemId and title to pass it with the event.

If I can successfully create a Menu object, it will be easy to get its children MenuItems.

Edit 2

I am not trying to display a menu at all, what I want is to populate a ListView with elements defined in a menu XML that have title, icon and itemId and whenever a ListViewItem is clicked I want to fire a onOptionsItemSelected(MenuItem item) event that is handled in my activity.

I know that I can parse the menu XML to extract items information, however I will not be able to fire onOptionsItemSelected(MenuItem item) without creating a standard MenuItem object to pass it as argument.

Any help will be appreciated. Thanks!

Answer

Musma picture Musma · Jul 14, 2014

Here's a trick to get an instance of Menu:

PopupMenu p  = new PopupMenu(getContext(), null);
Menu menu = p.getMenu();