Android Menus

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

idA resource id is the unique identity of the item, which is used to identify the resource.

iconIt is a reference to a drawable item to be used as the item’s icon.

titleIt is a reference to a string to be used as an item’s title.

showAsActionThis 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.

Options menu 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

publicbooleanonCreateOptionsMenu(Menu menu){

getMenuInflater().inflate(R.menu.main,menu);

returntrue;

}

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

publicbooleanonCreateOptionsMenu(Menu menu)

{

super.onCreateOptionsMenu(menu);

//inflate the menu and add items

getMenuInflater().inflate(R.menu.main,menu);

Stringtitle="Dynamic Menu";

intitemId=Menu.nonel

intitemOrder=1;

menu.add(groupId,itemId,itemOrder,title);

returntrue;

}

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

publicbooleanonOptionsItemSelected(MenuItem item){

// Handle item selection

switch(item.getItemId())

{

caseR.id.options_property1:

//do somethong

returntrue;

caseR.id.options_property2:

//do something

returntrue;

default:

returnsuper.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

publicbooleanonPrepareOptionsMenu(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 propertytotrueso it must notbe 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;

}

returntrue;

}

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 ModeThis 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.

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

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 event onCreateContextMenu() can perform some desired action provided in the implementation. This is where you inflate the menu resource.

1

2

3

4

5

6

7

@Override

publicvoidonCreateContextMenu(ContextMenu menu,Viewv,

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.

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

publicvoidshowPopup(Viewv){

PopupMenu popup=newPopupMenu(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(newView.OnLongClickListener(){

@override

publicbooleanonLongClick(Viewv){

doPopup();

returntrue;

}

});

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.