[Android] Defining a Context Menu for your View

In Building a Menu for your Android (V1.0 R1) App, a menu was created for an application. The context menu can create menus based on the current view that has focus.

In order to create context menus, the application needs to know which views will have a menu. This is done by calling registerForContextMenu with the view. In this example, a context menu will be created for two text views.

 1 package com.android.Context;
 2
 3 import android.app.Activity;
 4 import android.os.Bundle;
 5 import android.view.ContextMenu;
 6 import android.view.MenuItem;
 7 import android.view.View;
 8 import android.widget.TextView;
 9
10 public class Context extends Activity {
11   /**
12    * This will keep track of which item is selected.
13    */
14   public String checkedItem = "";
15   
16   @Override
17   public void onCreate(Bundle savedInstanceState) {
18     super.onCreate(savedInstanceState);
19     setContentView(R.layout.main);
20
21     registerForContextMenu(findViewById(R.id.primaryText));
22     registerForContextMenu(findViewById(R.id.secondaryText));
23   }
24

To set what gets displayed in the menu, the method onCreateContextMenu is overridden. This method will be told which view the context menu is being built for. Depending on the type of view that is passed in, the menuInfo parameter provides additional information. In this example, the information is not used.

25   public void onCreateContextMenu(
26       ContextMenu menu,
27       View v,
28       ContextMenu.ContextMenuInfo menuInfo)
29   {
30     // Show different menu items, depending on what is
31     // selected.
32     if (v.getId() == R.id.primaryText) 
33     {
34       menu.setHeaderTitle("Primary context");
35       addMenuItem(menu, "Primary 1", true);
36       addMenuItem(menu, "Primary 2", true);
37       addMenuItem(menu, "Primary 3", false);
38     }
39     else
40     {
41       menu.setHeaderTitle("Secondary context");
42       addMenuItem(menu, "Secondary 1", true);  
43       addMenuItem(menu, "Secondary 2", true);
44       addMenuItem(menu, "Secondary 3", false);
45     }    
46   }
47   
48   public MenuItem addMenuItem(ContextMenu menu,
49       String itemName,
50       boolean checkable)
51   {
52     MenuItem item = menu.add(itemName);
53     item.setCheckable(checkable);
54
55     if (itemName.equals(checkedItem))
56     {
57       item.setChecked(true);
58     }
59     return item;
60   }
61

Finally, to handle item selections from the context menu, the onContextItemSelected method is overridden. In the following example, the method will simply update a text view to display what was last selected.

62   public boolean onContextItemSelected(MenuItem item)
63   {
64     TextView statusText = (TextView) findViewById(R.id.statusView);
65     
66     if (item.isCheckable() == true)
67     {
68       // Visually display what is checked.
69       checkedItem = item.getTitle().toString();
70     }
71     
72     statusText.setText("Last item " + item.getTitle());
73     return true;
74   }
75 }
76

At line 57, notice the call to set the “checked” menu item, even though the method handling the event will also be given the menu item. It may seem like it is possible simply call the setChecked method in the onContextItemSelected method, but, if you try it with this example, you’ll notice that the menu item will NEVER be checked. This is because the method onCreateContextMenu will be called every time the context menu is going to be shown (with, possibly, a different instance of the ContextMenu). In doing so, a new instance of the menu items are added to the menu via the call to the addMenuItem method.

If you compare this example with that of Building a Menu for your Android (V1.0 R1) App, you’ll notice that they follow a similar pattern for setting up menus – override the menu creation method to control what gets shown in the menu and override the receiving selection event method to control what happens when an item is selected. In fact, this same pattern is followed for an options menu (override onCreateOptionsMenu to set what gets put in there).

Advertisements

8 Responses to [Android] Defining a Context Menu for your View

  1. vipendra says:

    Hi All, i Am new in Android and i am facin problem ..
    The following code is giving Error in R.id in each Statement.

    so plz respond me as soon as possible.

    • kahgoh says:

      Hi,

      I think this problem is arising because I create those source files using an older version of the SDK. I’m assuming you are using Eclipse. In any case, try the following:

      1) Right click on the project and then navigate like this properties -> android. Make sure that Android 1.5 is ticked. Close the dialog.

      2) Right click on the project again and then select Android Tools -> Fix Project Properties.

      3) Finally, from the main menu bar, select Project -> Clean. Make sure that Clean all projects is selected and click on OK.

      I’ve actually just tried this myself and it seems to have worked for me, although I’m just using version 1.5 of the SDK. If that doesn’t work for you, you can always resort creating your own project and copying the files in.

      Note that because the tutorial was written with an older version, you might have to update some parts for it work.

    • Ratheesh Valamchuzhy says:

      You must create the xml file and give the id to each text box and check the r.java file , if the id is listed or not

  2. sam says:

    hey … is it possible to open up a context menu without having to click a view? i want to display a list which has exactly the same view as a context menu has …. is there a way to do this ? anyone help me out …

  3. iddev says:

    Thanks for this tutorial 😀

  4. pavan says:

    Pavan @(pavanh)

    Very nice tutorial with efficent and detailed explaination, you can also check
    this one context menu

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: