Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Creating a Submenu

Published? true
FormatLanguage: WikiFormat

Problem:

Display options to the user in an floating window.

Solution:

Use a Submenu implementation and provide options to the user.

Discussion:

A submenu is a part of a menu that displays options in a hierarichal manner as opposed the style shown in a custom menu otherwise. The menus can be created in 2 ways: # By inflating an XML layout # Creating the menu items in the Java code. Following the second approach in this recipe, the creating menu/submenu items is done in the onCreateOptionsMenu() method.

We add the submenu to the menu using the addSubMenu() method. In order to prevent conflicts with other items in the menu, we explicitly provide group Id and item ID to the submenu we are creating (Constants for the item IDs and Group ID are specified). Then we set an icon for the submenu with setIcon method and an icon for the header of the Submenu.

To add items to the submenu we use the add() method. As arguments to the method, the group ID, item ID, the posiiton of the item in the submenu and the text associated with each item is specfied.


private static final int OPTION_1 = 0;
private static final int OPTION_2 = 1;
private int GROUP_ID = 4;
private int ITEM_ID =3;


@Override
public boolean onCreateOptionsMenu(Menu menu) {
   	
	SubMenu sub1 = menu.addSubMenu(GROUP_ID, ITEM_ID , Menu.NONE, R.string.submenu_1);
    sub1.setHeaderIcon(R.drawable.icon);
    sub1.setIcon(R.drawable.icon);
       
    sub1.add(GROUP_ID , OPTION_1, 0, "Submenu Option 1");
    sub1.add(GROUP_ID, OPTION_2, 1, "Submenu Option 2");
      
	return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
  	case OPTION_1: 
	    Toast.makeText(this, "Submenu 1, Option 1", Toast.LENGTH_LONG).show();
            break;
        case OPTION_2:
          	Toast.makeText(this, "Submenu 1, Option 2", Toast.LENGTH_LONG).show();
            break;
    }
        return true;
}

onOptionItemSelected() method is called when an item of the menu/submenu is selected. In this method, using switch-case we check for the item that is clicked and an apprpriate message is displayed.

Download:

The source code for this project can be downloaded from https://docs.google.com/leaf?id=0B_rESQKgad5LN2I5ZmIxNjEtYzc3Zi00MjczLTk5NzEtYmZjNzRlNjM1ZTc2&hl=en_US&authkey=CN-BsekI.