Context Menu Example for Android

Take Your First Steps in Implementing Context Menus in Android

In this tutorial we provide an Android context menu example, using the aptly named ContextMenu class. On a Windows PC system the context menu is sometimes referred to as the right-click menu. (Though using this term is no recommended in case the user is left handed and has switched the mouse, in which case the context menu requires the left-click!)

Android Calendar Context MenuA context menu is a menu of options that apply to the item immediately under the pointer (mouse or finger). For example in the Android Calendar the context menu can be used to add an event to the diary, for the selected hour press and hold until the menu appears. The parts required to implement a simple context menu are:

  1. Define the menu captions, usually in a string resource file.
  2. Define the menu layout in an XML file.
  3. Tell Android a View is using a context menu.
  4. When the context menu is requested show it.
  5. React to the selected menu item.

The example code presented here is going to call the setColorFilter method of an ImageView using a context menu. This will be used to add a basic image effect to a bitmap graphic by applying a red, blue or green filter. In this tutorial we are assuming that you have a working project in Eclipse to use as a base. If not see the article Displaying a Bitmap in Android to generate one.

Define Menu Captions

The menu captions are simple string resources. In Eclipse use the Package Explorer to select the res/values folder in the project. Use the File then New and Other menu option, under Android select Android XML Values File. Select Next and call the file something meaningful, such as color_menu_captions.xml, and click Finish. Add four strings with the values Red, Blue, Green and Clear. You will have a file similar to this:

[code lang=”XML”]<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="red_option">Red</string>
<string name="blue_option">Blue</string>
<string name="green_option">Green</string>
<string name="clear_option">Clear</string>
</resources>[/code]

(Tip: If copying our code see or article Copying Code from the Articles)

You could add the strings to the default strings.xml file if required, but it helps separating items into different files in projects to ease future maintenance.

Define the Menu XML

In a similar way to the first step create a new Android XML File under the res/menu folder. (If no menu folder is in the project select res and use the File and New then Folder menu option to create it.) Name the new menu file appropriately, such as color_menu.xml. The menu file has a menu element at the root and an item element for each menu option required. Each item has an id and title (the title points to the captions created above). The file will look like this:

[code lang=”XML”]<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/menu_red" android:title="@string/red_option" />
<item android:id="@+id/menu_green" android:title="@string/green_option"/>
<item android:id="@+id/menu_blue" android:title="@string/blue_option"/>
<item android:id="@+id/menu_clear" android:title="@string/clear_option"/>
</menu>[/code]

Tell Android a View Has a Context Menu

This is easy, one line of code that calls the Activity’s registerForContextMenu method passing in the View that needs the menu. Many Views can use the same context menu or different context menus, which menu to used is determined when it is requested to be created. Place this line of code at the bottom of the onCreate method in the Activity with the ImageView, if your ImageView has a different id change it appropriately :

[code lang=”Java”]registerForContextMenu((ImageView) findViewById(R.id.imageView1));[/code]

Here is the layout we used for our example (see the previously mentioned project).

[code lang=”XML”]<LinearLayout 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"
android:orientation="vertical"  >
<ImageView android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/simple_clown_240wide" />
</LinearLayout>[/code]

Royalty Free Simple Clown 240 Pixels WideThe bitmap used.

Show the Context Menu When Requested

The Activity handling the View that needs the context menu must override onCreateContextMenu. The View id (using the method getId) can be tested if it is needed to display different context menus. Here just the one is being used, notice how the call to inflate takes the name of the menu file:

[code lang=”Java”]@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.color_menu, menu);
}[/code]

Act on the Selected Item

Another override, called onContextItemSelected, the menu item selected is passed in, this is tested to perform the correct action:

[code lang=”Java”]@Override
public boolean onContextItemSelected(MenuItem item) {
ImageView imgv=(ImageView) findViewById(R.id.imageView1);
switch (item.getItemId()) {
case R.id.menu_red:
imgv.setColorFilter(Color.RED, PorterDuff.Mode.LIGHTEN);
return true;
case R.id.menu_blue:
imgv.setColorFilter(Color.BLUE, PorterDuff.Mode.LIGHTEN);
return true;
case R.id.menu_green:
imgv.setColorFilter(Color.GREEN, PorterDuff.Mode.LIGHTEN);
return true;
case R.id.menu_clear:
imgv.setColorFilter(null);
return true;
default:
return super.onContextItemSelected(item);
}
}[/code]

Applying Android Color Filter with a MenuTrue is returned when the menu has been correctly handled. Now when you hold down on the image a menu appears and you can select an option to apply a simple filter.

Adding a title to the menu is straightforward. Before the menu is inflated call the setHeaderTitle method:

[code lang=”Java”]@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Choose a filter");
getMenuInflater().inflate(R.menu.color_menu, menu);
}[/code]

(The setHeaderTitle method has a version that supports getting the the string from a resource file.)

Android Context Menu Title

This article has shown how straightforward it is to implement a context menu in an Android App. Give it a go.

Acknowledgements

The clown was drawn by Open Clip Art Library user shokunin.

One thought on “Context Menu Example for Android

Leave a Reply

Your email address will not be published. Required fields are marked *

Human Verification: In order to verify that you are a human and not a spam bot, please enter the answer into the following box below based on the instructions contained in the graphic.