Android OptionsMenu Tutorial

Menu is an important user interface component which provides some action options for a particular activity. In this post I’ll show the basics for setting up a menu.

The final output will look like this:

android options menu

The activity will contain 2 menu options: Add and Help. When clicking an option menu, a Toast notification will be displayed.


1. Create a new project in Eclipse:
Project: MenuTest
Activity: MenuTestActivity

2. Android provides a standard XML format to define menu items. So, instead of building the menu in the activity’s code, we will use the XML resource. Later, the XML resource is inflated in the code.

Inside the res/ folder create a new folder called menu. Inside the menu folder create a new XML file: options.xml

android options menu xml

3. Fill in the content of options.xml file with following code:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="" >


menu – defines the menu
item  – defines a menu item


4. Open the main Activity class and type following code:

public class MenuTestActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {

// Inflate the menu
public boolean onCreateOptionsMenu(Menu menu) {
   MenuInflater inflater = getMenuInflater();
   inflater.inflate(, menu);
   return true;

// Handle click events
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
      Toast.makeText(this, "Add", Toast.LENGTH_SHORT).show();
      return true;
      Toast.makeText(this, "Help", Toast.LENGTH_SHORT).show();
      return true;

      return super.onOptionsItemSelected(item);

– The onCreateOptionsMenu() method inflates your menu defined in the XML resource.

– The onOptionsItemSelected() method handle click events. When the user selects an item from the options menu, the system calls the onOptionsItemSelected() method. This method passes the MenuItem selected. The MenuItem can identify the item by calling the getItemId() which returns the unique ID for the menu item defined by the android:id attribute in the menu resource. Depending of the returned ID, we display the appropriate Toast notification.


5. Finally, run the application and click the “Menu” button on the emulator to launch the menu.

android menu button

4 thoughts on “Android OptionsMenu Tutorial

  1. nice tutorial.
    Can You help me in suggesting me a way to create submenus in android.
    Like say when i click on a menu item i need to display another submenu items beneath the menu

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s