Menus are a common user interface component in many types of applications. To provide a familiar and consistent user experience, you should use the Menu APIs to present user actions and other options in your activities.
Mobile Application Development-Android and It’s Tools
Android menus in android-chapter15
1. Chapter 15
Menus in Android
By
Dr. Ramkumar Lakshminarayan
Introduction
Menus are a common user interface component in many types of applications. To
provide a familiar and consistent user experience, you should use the Menu APIs to present
user actions and other options in your activities.
Menus
Beginning with Android 3.0 (API level 11), Android-powered devices are no longer
required to provide a dedicated Menu button. With this change, Android apps should migrate
away from a dependence on the traditional 6-item menu panel and instead provide an action
bar to present common user actions.
Although the design and user experience for some menu items have changed, the
semantics to define a set of actions and options is still based on the Menu APIs. The three
fundamental types of menus or action presentations on all versions of Android are:
Options menu and action bar
Context menu and contextual action mode
Popup menu
Options menu and action bar
The options menu is the primary collection of menu items for an activity. It's where
you should place actions that have a global impact on the app, such as "Search," "Compose
email," and "Settings."
Context menu and contextual action mode
A context menu is a floating menu that appears when the user performs a long-click
on an element. It provides actions that affect the selected content or context frame.
Popup menu
A popup menu displays a list of items in a vertical list that's anchored to the view that
invoked the menu. It's good for providing an overflow of actions that relate to specific
content or to provide options for a second part of a command. Actions in a popup menu
should not directly affect the corresponding content—that's what contextual actions are for.
Rather, the popup menu is for extended actions that relate to regions of content in your
activity.
2. Example Options Menu
Create a new application and name it as Optionmenu. In the activity_main.xml use the
default code:
In the resmenuactivity_main.xml add a menu item about as follows:
In Androidmanifest.xml add the following lines of code <uses-sdk> to allow the user
to access the internet.
In MainActivity.java OnOptionsItemSelected() is used to handle the menu selected.
URI class can both parse URI strings into parts and compose URI strings from parts.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/menu_settings"/>
<item android:id="@+id/about"
android:orderInCategory="101"
android:title="About" />
</menu>
<uses-permission android:name="android.permission.INTERNET"/>
3. Figure 15.1 Menu in Screen
package com.mjs.optionmenu;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
Intent intent =null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.rajaramsystems.com"));
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
4. When the About in the menu is clicked, the screen will navigate to a website. The
following screenshot shows the action when the About menu is clicked
Figure 15.2 About Menu Clicked
Example – Context Menu
In resmenumain_activity.xml add the following code to add the list of items.
In reslayoutactivity_main.xml add a button control with the following codes:
<menu
xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/menu_settings"/>
<item
android:id="@+id/menu_delete"
android:title="Delete Item"/>
<item
android:id="@+id/menu_copy"
android:title="Copy Item"/>
<item
android:id="@+id/menu_edit"
android:title="Edit Item"/>
</menu>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_alignParentTop="true"
android:layout_marginLeft="24dp"
android:text="Click Me !" />
5. Then make use of onCreateContextMenu() as well as onContextItemSelected() within
the Activity in order to inflate the menu and also handle user selection.
Using Custom Menu in Activity
In onCreate() add the button and assign the Event Listener with the following code:
When the code is executed and click the Click Me Button, Context Menu will be shown as
follows:
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.activity_main, menu);
menu.setHeaderTitle("Select an Option");
}
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_delete:
Toast.makeText(MainActivity.this,"Delete Operation is
performed!",Toast.LENGTH_SHORT ).show();
return true;
case R.id.menu_copy:
Toast.makeText(MainActivity.this,"Copy Operation is
performed!",Toast.LENGTH_SHORT ).show();
return true;
case R.id.menu_edit:
Toast.makeText(MainActivity.this,"Edit Operation is
performed!",Toast.LENGTH_SHORT ).show();
return true;
}
return super.onContextItemSelected(item);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
registerForContextMenu(btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openContextMenu(v);
}
});
}
6. Figure 15.3 Context Menu
Complete Code of MainActivity.java
package com.mjs.contextmenu;
import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
registerForContextMenu(btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openContextMenu(v);
}
});
}
@Override
public void onCreateContextMenu(ContextMenu menu, View
v,ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.activity_main, menu);
menu.setHeaderTitle("Select an Option");
}
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_delete:
Toast.makeText(MainActivity.this,"Delete Operation is
performed!",Toast.LENGTH_SHORT ).show();
return true;
case R.id.menu_copy:
Toast.makeText(MainActivity.this,"Copy Operation is
performed!",Toast.LENGTH_SHORT ).show();
return true;
case R.id.menu_edit:
Toast.makeText(MainActivity.this,"Edit Operation is
performed!",Toast.LENGTH_SHORT ).show();
return true;
}
return super.onContextItemSelected(item);
}
}
7. Popup Menu
Popup menus in android are useful for displaying extended options associated with a
specific action. For eg: ‘send’ action could have multiple extended options, like ‘send by
email’ or ‘send by sms’ etc. Unlike android context menus they can be invoked by any event
such a button click not just long clicks. They are associated with the specific view that
invoked it and each view in an activity can have its own popup window.
Creating the Popup Menu
Create a new instance of PopupMenu class and pass the instance of the Context (
usually the current activity) and the view (for which the pop-up menu is desired) as
arguments.
Inflate the menu resource using:
popupMenu.inflate () if you are using Android 4.0 SDK and above (or)
MenuInflater class (popupMenu.getMenuInflater().inflate() method) if you are using
Android 3.0 SDK
Call popupMenu.show() to display the menu
Override the popupMenu.setOnMenuItemClickListener () method and provide a call back
for handling user selections. The use selected menu item is passed in as argument to the
callback method.
Create a new project with the name Popupmenu and use the following code for
reslayoutactivity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<Button android:id="@+id/popupMenuBtn"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Show me the Popup"
android:layout_gravity="center"
android:gravity="center"/>
</RelativeLayout>
8. In resmenuactivity_main.xml, add the following lines of code:
In resvaluescolor.xml create the values for colors using the following code:
In resvaluesstrings.xml change the value for hello world as “Example for popup
Menu” and change the code as follows:
In MainActivity.java ensure that the following packages are used and use the code as
follows:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/menu_red" android:title="Red" />
<item android:id="@+id/menu_green" android:title="Green"/>
<item android:id="@+id/menu_blue" android:title="Blue"/>
</menu>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#ff0000</color>
<color name="green">#00ff00</color>
<color name="blue">#0000ff</color>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Popmenu</string>
<string name="hello_world">Example for Popup Menu</string>
</resources>
import android.os.Bundle;
import android.app.Activity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
9. Code of MainActivity.java for popup menu
public class MainActivity extends Activity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* A Button that acts as the view element for the popup menu.
*/
final Button btn = (Button) findViewById(R.id.popupMenuBtn);
/**
* Step 1: Create a new instance of popup menu
*/
final PopupMenu popupMenu = new PopupMenu(this, btn);
/**
* Step 2: Inflate the menu resource. Here the menu resource is
* defined in the res/menu project folder
*/
popupMenu.inflate(R.menu.activity_main);
/**
* Step 3: Call show() method on the popup menu to display the
* menu when the button is clicked.
*/
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupMenu.show();
}
});
/**
* Handle menu item clicks
*/
popupMenu.setOnMenuItemClickListener(
new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_red:
btn.setBackgroundResource(R.color.red);
break;
case R.id.menu_blue:
btn.setBackgroundResource(R.color.blue);
break;
case R.id.menu_green:
btn.setBackgroundResource(R.color.green);
break;
}
return true;
}
});
}
}
10. Figure 15.4 Popup Menu.
When the Red Option is clicked the button color will be changed to Red and it is
applicable for Green and Blue Button also.
Summary
In this unit we have seen Menus are a common user interface component in many
types of applications. We have seen the examples of creating application with Options Menu,
Context and Popup Menu.