Working with Submenus

Let's take a look at Android's submenus now. Figure 5-1 points out the structural relationship of a SubMenu to a Menu and a MenuItem. A Menu object can have multiple SubMenu objects. Each SubMenu object is added to the Menu object through a call to the Menu.addSubMenu method (see Listing 5-14). You add menu items to a submenu the same way that you add menu items to a menu. This is because SubMenu is also derived from a Menu object. However, you cannot add additional submenus to a submenu.

Listing 5-14. Adding Submenus private void addSubMenu(Menu menu) {

//Secondary items are shown just like everything else int base=Menu.FIRST + 100;

SubMenu sm = menu.addSubMenu(base,base+1,Menu.NONE,"submenu"); sm.add(base,base+2,base+2,"sub iteml"); sm.add(base,base+3,base+3, "sub item2"); sm.add(base,base+4,base+4, "sub item3");

//submenu item icons are not supported item1.setIcon(R.drawable.icon48x48_2);

//the following is ok however sm.setIcon(R.drawable.icon48x48_l);

//This will result in a runtime exception //sm.addSubMenu("try this");

Note A SubMenu, as a subclass of the Menu object, continues to carry the addSubMenu method. The compiler won't complain if you add a submenu to another submenu, but you'll get a runtime exception if you try to do it.

The Android SDK documentation also suggests that submenus do not support icon menu items. When you add an icon to a menu item and then add that menu item to a submenu, the menu item will ignore that icon, even if you don't see a compile-time or runtime error. However, the submenu itself can have an icon.

0 0

Post a comment