More on menus

The notepad application we are constructing only scratches the surface with menus.

You can also add shortcut keys for menu items, create submenus and even add menu items to other applications!

Fill out the body of the onCreateOptionsMenu() method.

We will now create the "Add Item" button that can be accessed by pressing the menu button on the device. We'll specify that it occupy the first position in the menu.

1. In strings.xml resource (under res/values), add a new string named "menujnsert" with its value set to Add Item:

<string name="menu insert">Add Item</string>

Then save the file and return to Notepadv1. 2. Create a menu position constant at the top of the class:

public static final int INSERT_ID = Menu.FIRST;

3. In the onCreateOptionsMenu() method, change the super call so we capture the boolean return as result. We'll return this value at the end.

4. Then add the menu item with menu.add() . The whole method should now look like this:

@Override public boolean onCreateOptionsMenu(Menu menu) {

boolean result = super


menu.add(0, INSERT ID,

0, insert);


return result;

The arguments passed to add() indicate: a group identifier for this menu (none, in this case), a unique ID (defined above), the order of the item (zero indicates no preference), and the resource of the string to use for the item.

0 0

Post a comment