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);
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With