To create the menu in Android application you need to do the following two steps:
- Define menu in the XML file.You add all the menu sub items which you want to add to the menu.You add the menu items using the item XML element.
- Override the onCreateOptionsMenu() method in the Activity subclass.This attaches the menu that you defined in the XML file to the Activity class.
Following is a simple example of defining menu items in a XML file.
1.In XML file of the menu you define the menu structure. This consists of <item> XML element.these XML elements represents the individual menu items.The root element should be <menu>.
Within menu xml element you define the menu items using the item xml element <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/save" android:title="Save" android:icon="@drawable/saveIcon" /> <item android:id="@+id/delete" android:title="Delete" android:icon="@drawable/deleteIcon" /> </menu>
2.In the activity subclass you override the onCreateOptionsMenu() method to create the menu which you have defined in the XML file in step 1 above.
@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; }
When you return true from the onCreateOptionsMenu method ,it causes the menu to be displayed.
The MenuInflater class is used to create Menu objects from the XML file.After retrieving an object of MenuInflater class,we are calling the inflate() method.In the inflate() method we are passing the menu id and the menu object received as method argument.
Leave a Reply