Introduction to Android Menus
Android menus are user interface elements of any element. As interface plays the main role in any application. If the interface of any application is not understandable and user experience is not good, then if the application can solve a rocket science it is of no use for the user. Almost all the applications use menus. In Android after version, 3.0 users got rid of the traditional menu button. Action bar started providing the features of the menu button.
Why use Android Menus
Menus are used to make Android users comfortable and to make the layout understandable. Android menus combine the similar items together. For example, if all the functions like add, update, delete are displayed with every individual contact item in the phonebook, then it will give a very messy impression to the user. So Android provides a feature when user taps or long tap on any item it displays a menu for related operations.
How to use Android Menus
For all the types of menus, you should place a separate XML file in the res->menu folder. As Android provides a standard XML format to define menu which must be placed in an XML menu resource. You can also dynamically create an options menu in your code.
To use the Android menu, you can inflate it in your activity by loading it as a menu object.
Components of XML menu resource
XML menu in Android consists of the following components.
<menu>
This tag is used to define a menu, which is a container for the menu items. A menu item must be the root node for the file and can hold one or more items and groups.
<item>
This tag is used to create a menu item, which represents a single item in the menu. You can create a sub menu by creating a nested menu element.
<group>
Group tag is optional in Android menus. The group is the invisible container for item element. It allows you to categorize menu items so that items can share similar properties like active state and visibility.
Syntax of Android Menus
1 2 3 4 5 6 |
<menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/action_settings“ android:orderInCategory="100" android:showAsAction="never" android:title="@string/action_settings"/> </menu> |
Attributes of XML Menu Resources
id
A resource id is the unique identity of the item, which is used to identify the resource.
icon
It is a reference to a drawable item to be used as the item’s icon.
title
It is a reference to a string to be used as an item’s title.
showAsAction
This attribute specifies when and how the item should appear as an action item in the action bar.
Types of Menus in Android
There are three types of menus in Android
- Options Menu
- Context Menu
- Popup Menu
Options Menu
The options menu is the global menu for the Android application. The user can view options menu in all the activities of an android application. So you can say that it has a global impact on the Android application. The options menu is the primary collection of the menu items in Android.

In the options menu, actions and other relevant options are placed. By default system places all the items in the action bar, i.e. action overflow. The user can open options menu through the action overflow icon in the top right corner of the screen. To enable quick access, you can also promote some items to appear in the action bar by adding.
1 |
android:showAsAction="ifRoom" |
Creating Options Menu
To specify the options menu for an activity override onCreateOptionsMenu()
In this method, you can inflate your menu resource (defined in XML) into the Menu provided in the callback.
Syntax
You can inflate menu in your code through
1 2 3 4 |
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } |
Creating Options Menu through XML
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/options_property1" android:title="Property 1" /> <item android:id="@+id/options_property2" android:title="Property 2" /> </menu> |
Dynamically Create Options Menu
If you want to dynamically create an Options Menu you must overload onCreateOptionsMenu() method with Menu object as parameters. To add an item to the menu, menu.add() method is used which takes 4 parameters i.e. Item group Id, Item Id, Item order(Menu.NONE if the order is not important) and Title of the item.
You must call this method through the super class as it adds some additional system options.
1 2 3 4 5 6 7 8 9 10 11 12 |
@override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); //inflate the menu and add items getMenuInflater().inflate(R.menu.main, menu); String title = "Dynamic Menu"; int itemId = Menu.nonel int itemOrder = 1; menu.add(groupId, itemId, itemOrder, title); return true; } |
Handling the Click Events of Options Menu
Whenever the user selects an item from the options menu (including action items in the action bar), the system calls the method.onOptionsItemSelected()
This method passes the MenuItem selected. You can identify the item by calling, getItemId()
which returns the unique ID for the menu item. When you successfully handle a menu item, it returns true. If you don’t handle the menu item, you should call the superclass implementation of its onOptionsItemSelected()
method. Its default implementation returns false.
Syntax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.options_property1: //do somethong return true; case R.id.options_property2: //do something return true; default: return super.onOptionsItemSelected(item); } } |
Updating Options Menu Dynamically
In case if you want to update an options menu on run-time i.e. If you want to dynamically update options menu, you must override onPrepareOptionsMenu()
method. This method is called before the menu is shown. By using this method you can dynamically add, update or remove options from the options menu. You can also enable/disable and manage the visibility of the menu items.
To execute onPrepareOptionsMenu()
, you must call supportInvalidateOptionsMenu()
. In the below example you will learn how to dynamically add and remove a menu item.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@override public boolean onPrepareOptionsMenu(Menu menu) { Log.i(TAG, "Updating Menu Items");//Maintain log of actions if(isItemOneSelected && !isItemAdded)//check whether the item is selected or not and whether new item is already added or not { Log.i(TAG, "Adding New Item in Menu");//Maintain log of actions menu.add(0, MENU_ITEM+1, Menu.NONE, "New Item");//adding a new item in the menu isItemAdded=true;setting the Item added property to true so it must not be added again } if(isRemoveItem)//check if item is already deleted or not { Log.i(TAG, "Removing Old Item in Menu");//Maintain log of actions menu.removeItem(MENU_ITEM+1);//remove item from the menu items //setting the properties for the checks isRemoveItem=false; isItemOneSelected=false; isItemAdded=false; } return true; } |
Context Menu
A context menu only affects the only specific item or the context in the user interface. You can use the context menu for any view but most of the time context menus are used for ListView and GridView along with other View Groups in which the user can perform direct actions on each of the items.
You can use context menu through two different ways
- Floating Context Menu
A menu appears as a floating list of menu items in the floating context menu. As it is shown in the dialog box, when the user long clicks on any view which provides some actions on the view. The user can only perform one contextual action at a time. - Contextual Action Mode
This mode is the default system implementation of the action mode which displays a context action bar at the top of the screen. These actions are only for the selected item/items.
Creating a Context Menu
Contextual action mode
The contextual menu is only available on Android 3.0 and above, and it is the preferred technique for contextual actions when available. If the Android version is lower than 3.0, then you should fall back to floating context menu.

The Contextual action mode is the system implementation of ActionMode. Contextual mode focuses the menu bar on the screen for the user action.
Action Mode: Action mode provides alternate ways of displaying menus.
Create Context Menu in XML
Create a new menu in res -> menu folder. In XML create a menu and place items as required.
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/context_property1" android:title="Property 1" /> <item android:id="@+id/context_property1" android:title="Property 1" /> </menu> |
Create Context Menu using ListView
You can also populate your context menu using ListView. In this case, you will need to use ArrayAdapter and an instance of ListView and add items to it using setAdapter()
method.
1 2 3 4 5 6 7 |
String[] aboutlist; //array of String containing list items aboutlist = getResources().getStringArray(R.array.aboutlist); //get resources from the string array ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,aboutlist);//using array adapter ListView listview = (ListView) findViewById(R.id.listView1);// creating instance of list view listview.setAdapter(adapter);//populating list view |
Create and Use Floating Context Menu
If you want to create floating context menu then you must follow the steps below
- Register the view to which context menu should be associated by using
registerForContextMenu()
method and passing the view as parameters.
12345678910String[] aboutlist;aboutlist = getResources().getStringArray(R.array.aboutlist);ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,aboutlist);ListView listview = (ListView) findViewById(R.id.listView1);listview.setAdapter(adapter);registerForContextMenu(listview); //register for context view and passing list view as parameter - Implement and override
onCreateContextMenu()
method, so when the view gets a long-click eventonCreateContextMenu()
can perform some desired action provided in the implementation. This is where you inflate the menu resource.
1234567@Overridepublic void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {super.onCreateContextMenu(menu, v, menuInfo);MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.about_menu, menu);} - Implement
onContextItemSelected()
method so when the user selects any menu item, this method calls and perform some desired functionality.
1234567891011121314151617@Overridepublic boolean onContextItemSelected(MenuItem item) {AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();switch (item.getItemId()) {case R.id.context_property1:{//display toast on item selectedToast.makeText(getApplicationContext(), "Edit: " + info.position, Toast.LENGTH_SHORT).show();return true;}default:{return super.onContextItemSelected(item);}}}
Popup Menu
A popup menu is anchored to the view and also known as the modal menu. It appears below the anchor view if some space is available otherwise above the view depending upon the space.
You can provide an overflow style menu that includes actions for specific content and it can also be used for a drop down menu same like a spinner which does not retain a specific position.
Creating a Popup Menu
Create an XML file in res->menu folder. Add menu items in XML file as required.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/popup_choice1" android:title="@string/popup_choice1"/> <item android:id="@+id/popup_choice2" android:title="@string/popup_choice2"/> <item android:id="@+id/popup_choice3" android:title="@string/popup_choice3"/> </menu> |
Create and Implement Button to Show Popup Menu
Add a button in your Layout file to display Popup Menu.
1 2 3 4 5 6 7 8 9 10 11 12 |
<RelativeLayout> <Button android:id="@+id/btn_popup" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="20dp" android:layout_marginTop="20dp" android:text="@string/btn_popup" android:onClick="showPopup" /> </RelativeLayout> |
In XML file as the onClick event is showPopup, implement the method to show Popup menu i.e. to inflate the menu and show the popup menu.
1 2 3 4 5 6 7 8 |
public void showPopup(View v) { PopupMenu popup = new PopupMenu(this, v); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.popup, popup.getMenu()); popup.show(); } |
Display Popup Menu using ImageView
You can also display your popup menu using ImageView. As if you want the Popup menu to open when user long taps on any image. So you can do this by implementing setOnLongClickListener()
and overriding method onLongClick()
with an instance of View
as parameters and return type as boolean
.
1 2 3 4 5 6 7 8 |
ImageView image=(ImageView) findViewById(R.id.image); image.setOnLongClickListener(new View.OnLongClickListener() { @override public boolean onLongClick(View v) { doPopup(); return true; } }); |
Handling Click Events on Menu Items in Popup Menu
When you want to some functionality to be performed on popup options click you must implement setOnMenuItemClickListener()
with an object of PopupMenu.OnMenuItemClickListener()
And override method onMenuItemClick()
with an object of MenuItem
as parameters and return type as boolean
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.popup_choice1: Toast.makeText(getApplicationContext(), item.getTitle(),Toast.LENGTH_SHORT).show();//make toast on item select return true; default: return false; } } }); |
Hope that you find this tutorial helpful give your feedback in the comments.
Stay Tuned for More Upcoming Android Tutorials and Lessons.