Option Menu in Android


We have seen a "Menu" button in an android screen, but how is it useful and how can we create a menu in android application? This article will help you to do the same.

Building Menus in an Android Application

Menu is generally used to  give extra functionality to an application. One perfect example is, while we are making a phone call, we may want to see other contacts or messages. This is where the Option Menu comes in picture. This can be done using the same.

Menu has 3 types:

  1. Option Menu (Visible if touch "Menu" button)
  2. Context Menu (Visible if long press on any View. View is anything like Button, EditText)
  3. Sub Menu

The following tutorial will guide you towards creating this kind of application step by step.

Step 1: Add "optionmenu.xml"

Right Click on "project" -> New -> Andorid Xml File


Step 2: Edit "optoinmenu.xml"

This file contains items to be displayed. It takes the "id" that uniquely identify that item and the "title" that displays on  screen.

To edit that file

Your Project -> res -> menu -> optionmenu.xml

<?xml version="1.0" encoding="utf-8"?>
    <item android:id="@+id/Color" android:title="Color">
            <item android:id="@+id/RedColor" android:title="Red"/>
            <item android:id="@+id/GreenColor" android:title="Green"/>

Step 3: Edit "MenuOptionDemoActivity.java"


package com.MenuOptionDemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class MenuOptionDemoActivity extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
  public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater=getMenuInflater();
        inflater.inflate(R.menu.optionmenu, menu);
        return super.onCreateOptionsMenu(menu);
public boolean onOptionsItemSelected(MenuItem item) {
  // TODO Auto-generated method stub
            Toast.makeText(MenuOptionDemoActivity.this,"Red Color Selected" ,1000).show();
else if(item.getItemId()==R.id.GreenColor)
            Toast.makeText(MenuOptionDemoActivity.this, "Green Color Selected", 1000).show();
return super.onOptionsItemSelected(item);


In this java file, "onCreateOptionMenu" used to create option menu and "onOptionsItemSelected" used to listen which item is selected by user.

Step 4: Start Emulator





In this brief tutorial, we discussed how create menus in an Android application.


Up Next
    Ebook Download
    View all
    View all