Working with Icon Menus

Now that we've hinted at icon menus, let's talk about them in more detail. Android supports not only text, but also images or icons as part of its menu repertoire. You can use icons to represent your menu items instead of and in addition to text. But note a few limitations when it comes to using icon menus. First, as you saw in the previous paragraph, you can't use icon menus for expanded menus. Second, icon menu items do not support menu-item check marks. Third, if the text in an icon menu item is too long, it will be truncated after a certain number of characters depending on the size of the display. (This last limitation applies to text-based menu items also.)

Creating an icon menu item is straightforward. You create a regular text-based menu item as before, then you use the setIcon method on the MenuItem class to set the image. You'll need to use the image's resource ID, so you must generate it first by placing the image or icon in the /res/drawable directory. For example, if the icon's file name is balloons, then the resource ID will be R.drawable.balloons.

Here is some sample code that demonstrates this:

//add a menu item and remember it so that you can use it //subsequently to set the icon on it.

MenuItem item8 = menu.add(base,base+8,base+8,"uncheck secondary"); item8.setIcon(R.drawable.balloons);

As you add menu items to the menu, you rarely need to keep a local variable returned by the menu.add method. But in this case, you need to remember the returned object so you can add the icon to the menu item. The code in this example also demonstrates that the type returned by the menu.add method is MenuItem.

The icon will show as long as the menu item is displayed on the main application screen. If it's displayed as part of the expanded menu, the icon will not show. The menu item displaying an image of balloons in Figure 5-2 is an example of an icon menu item.

0 0

Post a comment