Recipe Building Menus

A developer can implement three types of menus in Android, and this recipe creates an example of each:

■ Options menu—The main menu for an Activity that displays when the MENU key is pressed. It contains an Icon menu and possibly an Expanded menu when the More menu item is selected.

■ Context Menu—A floating list of menu items that displays when a view is long pressed.

■ Submenu—A floating list of menu items that displays when a menu item is pressed.

The Options menu is created the first time the MENU key is pressed in an activity. This launches the onCreateOptionsMenu() method that usually contains Menu methods, such as:

menu.add(GROUP_DEFAULT, MENU_ADD, 0, "Add") •setIcon(R.drawable.icon);

The first argument of the add() method labels the group of the menu item. Groups of items can be manipulated together. The second argument is an integer ID that represents the menu item. It is passed to the callback function to determine which menu item was selected.The third argument is the order of the item in the menu. If it is not used, the order falls back to the order the items were added to the Menu object.The last argument is the text that displays with the menu item. It can be a String or a string resource such as R.string.myLabel.This is the only menu that also supports adding icons to the menu choices using the setIcon() method.

This method is called only once, and the menu does not need to be built again for the rest of the activity. However, the onPrepareOptionsMenu() can be used if any of the menu options need to change during run-time.

When an item from the options menu is clicked, the onOptionsItemSelected() method is called. This passes the selected item ID, and a switch statement can be used to determine which option was selected.

For this recipe, the options are to add a note, delete a note, or send a note. These are represented as simple mock functions that increment a counter (itemNum), decrement a counter, or show a Toast to the screen of the current counter value.To show an example of changing the menu options at run-time, the delete option is available only if a note has already been added in the past. This is done by grouping the delete option in a separate group and hiding the group when the itemNum is zero. The activity is shown in Listing 5.2.

Listing 5.2 src/com/cookbook/building_menus/ package com.cookbook.building_menus;

import; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View;

import android.view.ContextMenu.ContextMenulnfo;

import android.widget.TextView; import android.widget.Toast;

public class BuildingMenus extends Activity {

private final int MENU_ADD=1, MENU_SEND=2, MENU_DEL=3; private final int GROUP_DEFAULT=0, GROUP_DEL=1; private final int ID_DEFAULT=0;

private final int ID_TEXT1=1, ID_TEXT2=2, ID_TEXT3=3;

private String[] choices = {"Press Me", "Try Again", "Change Me"};

private static int itemNum=0; private static TextView bv;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); bv = (TextView) findViewById(;

registerForContextMenu((View) findViewById(;

@Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(GROUP_DEFAULT, MENU_ADD, 0, "Add")

.setlcon(R.drawable.icon); //example of adding icon menu.add(GROUP_DEFAULT, MENU_SEND, 0, "Send"); menu.add(GROUP_DEL, MENU_DEL, 0, "Delete");

return super.onCreateOptionsMenu(menu);

@Override public boolean onPrepareOptionsMenu(Menu menu) { if(itemNum>0) {

menu.setGroupVisible(GROUP_DEL, true); } else {

menu.setGroupVisible(GROUP_DEL, false);

return super.onPrepareOptionsMenu(menu);

@Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case MENU_ADD:

create_note(); return true; case MENU_SEND: send_note(); return true; case MENU_DEL:

delete_note(); return true;

return super.onOptionsltemSelected(item);

@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenulnfo menulnfo) { super.onCreateContextMenu(menu, v, menulnfo); if(v.getId() == {

SubMenu textMenu = menu.addSubMenu("Change Text"); textMenu.add(0, ID_TEXT1, 0, choices[0]); textMenu.add(0, ID_TEXT2, 0, choices[1]); textMenu.add(0, ID_TEXT3, 0, choices[2]); menu.add(0, ID_DEFAULT, 0, "Original Text");

@Override public boolean onContextItemSelected(MenuItem item) { switch(item.getItemId()) { case ID_DEFAULT:

bv.setText(R.string.hello); return true; case ID_TEXT1: case ID_TEXT2: case ID TEXT3:

bv.setText(choices[item.getItemId()-1]); return true;

return super.onContextltemSelected(item);

void create_note() { // mock code to create note itemNum++;

void send_note() { // mock code to send note Toast.makeText(this, "Item: "+itemNum, Toast.LENGTH_SHORT).show();

void delete_note() { // mock code to delete note itemNum—;

The activity in Listing 5.2 also shows an example of a context menu and submenu.A TextView focus_text is added to the layout, as shown in Listing 5.3, and registered for a context menu using the registerForContextMenu() function in the onCreate() method of the activity.

When the view is pressed and held, the onCreateContextMenu() method is called to build the context menu. Here, the SubMenu is implemented using the addSubMenu() method for the Menu instance. The submenu items are specified along with the main menu items, and the onContextItemSelected() method is called when an item from either menu is clicked. Here, the recipe shows a change of text based on the menu choice.

Listing 5.3 res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="" android:orientation="vertical" android:layout_width="fill_parent"

android:layout_height="fill_parent" >

<TextView android:id="@+id/focus_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="40sp" android:text="@string/hello" />


Figures 5.1 and 5.2 show how the menus look for the different cases.

Linearlayout Hide
Figure 5.1 Options menu (top) and an added option at run-time (bottom).



Hello World, BuildingMenus!

Change Text Original Text

Try Again

^ Change Text

Press Me Try Again Change Me

Figure 5.2 The Context menu that displays with a long click on the text (left) and the submenu for the Change Text option that provides three alternate strings for the text view (right).

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook

Post a comment