How exactly does the MenuInflater work?

PenguinCake

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);
}
Antoine Marques

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related