The options menu is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app, such as "Search," "Compose email" and "Settings."
It has 3 elements as explained below:
Menu, is a container for menu items. A <menu> element must be the root node for the file and can hold one or more <item> and <group> elements.
<item> creates a MenuItem, which represents a single item in a menu. This element may contain a nested <menu> element in order to create a submenu.
|android:id||A unique resource ID.|
|android:title||The menu title as a string resource or raw string.|
|android:titleCondensed||This title is used for situations in which the normal title is too long.|
|android:icon||An image to be used as the menu item icon.|
|android:onClick||The method to call when this menu item is clicked. The method must be declared in the activity as public and accept a MenuItem as its only parameter, which indicates the item clicked.|
specify when and how this item should appear as an action item in the app bar.
define the item's priority. Possible values are:
|android:orderInCategory||The order of "importance" of the item, within a group.|
A menu group is an invisible container, share common properties like visible, enabled, checkable etc. It can contain one or more <item> elements and it must be a child of a <menu> element.
To add an options menu in an Activity, you must override onCreateOptionsMenu method which is called only once.
Here are 2 ways, you can create option menu:
my_menu is the name of menu resource file
Sometimes, we need to change option menu at runtime, but problem is onCreateOptionsMenu method is called only once, so how we can do this task.
call ActivityObject.invalidateOptionsMenu(), as the name suggests that will invalidate the current menu and consequently ActivityObject.onPrepareOptionsMenu() will be called again. So, override onPrepareOptionsMenu method and place menu creation code.Example is:
When a menu item is clicked onOptionsItemSelected method is called. This is the place where you will write your click handler code.
If you've declared onClick attribute of Menu item in menu resource, then you will create a method with the same name in your activity and will place your click handler code there.
Step 1: Create a new project in Android Studio and name it Android Options Menu.
Step 2: Create a folder menu inside res directory if it is not already present.
Step 3: Open res -> menu and add a new menu resource file with a name
Step 4: Open MainActivity.java and replace its code with below given code.
Step 5:Clean and run your project to see the result.