Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly does the MenuInflater work?

Tags:

java

android

If I get it right this far, MenuInflater is a type of object that can inflate (blow up, expand?) a Menu type object. But when is the method called and which Menu object is automatically passed in? What does getMenuInflater() do (or is it just another way of ... = new MenuInflater())? And then once the inflater object is created, what exactly does the .inflate do? What does the passed-in menu object do with my main.xml menu?

(I'm sorry if I'm asking too many questions at once.)

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(Menu);
}
like image 603
PenguinCake Avatar asked Aug 07 '14 09:08

PenguinCake


2 Answers

A MenuInflater is an object that is able to create Menu from xml resources (of course only menus resources), that is : construct a new instance of Menu given a menu resource identifier.

The onCreateOptionMenu(Menu) is called when the menu button of the device is pressed, or either Activity.openOptionsMenu() is called.

The actual rendering of the menu is handled by the activity. Just before it is shown, the Activity passes to you the menu so that you can fill it with your own items, then shows it.
So Android undertakes that since it's not your business to render the menu, you shall not control what menu is actually passed to you inside onCreateOptionsMenu.


As for the ActionBar, the onCreateOptionsMenu is called when filling ActionBar, so that options from the menu be available in the ActionBar. This method is only called once after the Activity be created. If you want to modify the menu later, you should instead override Activity.onPrepareOptionsMenu

like image 117
Antoine Marques Avatar answered Nov 15 '22 17:11

Antoine Marques


My understanding about "inflating" is "reading" a resource file (a XML file which describes a layout or GUI element) and "creating" the actual objects that correspond to it; this will make the menu object visible within an Android application. MenuInflater class represents an Android framework class specialized in parsing and constructing menus from menu resource files.

Have a look at: Build Menus in Android with Java and XML: Introduction

From the article:

Once the menu resource file (my_menu.xml) is ready and has all the items you intend to add, you can use MenuInflater to override the function onCreateOptionsMenu. This function is supposed to fill the menu object with the desired menu items, but Android’s MenuInflater class helps you create menu items from the XML resource mentioned above

like image 25
Adrian Avatar answered Nov 15 '22 17:11

Adrian