Android Dialogs and onContextItemSelected()

ListViews and GridViews are great widgets to use in an Activity for your app. Sometimes it is useful to also create smaller versions of them for dialogs within your app. There’s only one problem: Context Menus. If you have tried to put a context menu on a ListView inside a dialog, you may have found out that while onCreateContextMenu() is called, onContextItemSelected() is not. There is a workaround, though, because onContextItemSelected() is actually a convenience method called from onMenuItemSelected(int, MenuItem). If you add the following method to your dialog containing the ListView (or GridView), you will find that onContextItemSelected() is working again.

public boolean onMenuItemSelected(int aFeatureId, MenuItem aMenuItem) {
    if (aFeatureId==Window.FEATURE_CONTEXT_MENU)
        return onContextItemSelected(aMenuItem);
        return super.onMenuItemSelected(aFeatureId, aMenuItem);


Using a SubMenu in a ListActivity’s Context Menu

One of the limitations of Android’s ListActivity’s Context Menu is that if your context menu gets too large to fit comfortably into one list, shortening it by putting several items into SubMenus requires special handling in onContextItemSelected().

Context menus, by definition, are transient and will be thrown away as soon as they disappear from view. Once you click on a MenuItem that displays a SubMenu, clicking any item in that SubMenu will call the onContextItemSelected(), as expected. What is not expected is that the standard call to get the MenuInfo will return null. Continue reading