Add and Handle Menu Items

2 votes · 2 comments

This code adds two items to the menu (Help and About) and handles the selection of the items.

raw ·
copy
· download
public class TestProject extends Activity { /* Set ID's */ private final int MENU_NEW_GAME = 0; private final int MENU_QUIT = 1; /* Create Menu Items */ public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_NEW_GAME, 0, "Help"); menu.add(0, MENU_QUIT, 0, "About"); return true; } /* Handles Item Selection */ public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_NEW_GAME: newGame(); return true; case MENU_QUIT: finish(); return true; } return false; } }
Add a comment

2 Comments

Just wanted to add, that you can include an image to the menu as simple as using the following code at line 8:

menu.add(0, MENU_NEW_GAME, 0, "Help").setIcon(R.drawable.icon_menu_newGame);

Reply · April 18, 2009, 10:43 p.m.

Thanks, this worked great. I don't understand why it's so hard to find SIMPLE code examples.

Reply · May 26, 2009, 12:53 a.m.