Submenus

A sub menu can be added within any menu, except another sub menu. These are very useful when your application has a lot of functions that may be organized in topics, like the items in a PC application's menu bar (File, Edit, View, etc.).

A sub menu is created by adding it to an existing Menu with addSubMenu() . This returns a SubMenu object (an extension of Menu). You can then add additional items to this menu, with the normal routine, using the add() methods. For example:

public boolean onCreateOptionsMenu(Menu menu) {

boolean result = super.onCreateOptionsMenu(menu); SubMenu fileMenu = menu.addSubMenu("File"); SubMenu editMenu = menu.addSubMenu("Edit"); fileMenu.add("new");

return true; case DELETE_ID:

deleteNote(info.id); return true; default:

return super.onContextItemSelected(item);

}

fileMenu

add("open");

fileMenu

add("save");

editMenu

add("undo");

editMenu

add("redo");

return result;

}

Callbacks for items selected in a sub menu are made to the parent menu's callback method. For the example above, selections in the sub menu will be handled by the onOptionsItemSelected() callback.

You can also add Submenus when you define the parent menu in XML.

0 0

Post a comment