Introduction
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:
- Option Menu (Visible if touch "Menu"
button)
- Context Menu (Visible if long press on any
View. View is anything like Button, EditText)
- 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"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/Color"
android:title="Color">
<menu>
<item android:id="@+id/RedColor"
android:title="Red"/>
<item android:id="@+id/GreenColor"
android:title="Green"/>
</menu>
</item>
</menu>
-----------------
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. */
@Override
public void
onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean
onCreateOptionsMenu(Menu
menu) {
// TODO
Auto-generated method stub
MenuInflater
inflater=getMenuInflater();
inflater.inflate(R.menu.optionmenu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean
onOptionsItemSelected(MenuItem
item) {
// TODO
Auto-generated method stub
if(item.getItemId()==R.id.RedColor)
{
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
Summary
In this brief tutorial, we discussed how create menus in an Android application.