Tuesday, September 21, 2010

Solution to: onContextItemSelected not called after selecting a context menu

Here is a solution to Android development problem, where the onContextItemSelected method is not called even after you see the context menu popup and selecting one of the items there.

1. Make sure that registerForContextMenu has been called, with the parameter the view you have the context menu on. For ListActivity with a context menu on the items, call registerForContextMenu(getListView()).

2. If you have an options menu on your activity (the one that pops up from the bottom of the screen when you press the hardware/softshell MENU button, you may be interrupting the event flow when you override onMenuItemSelected method. Overriding the onMenuItemSelected was taught in the Notepad v2 tutorial source code. That was partially wrong. You should not override it, instead you should override onOptionsItemSelected, and return false when the menu item is not handled. Example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.menuImpor) {
        // do your work...
        return true;
    } else if (item.getItemId() == R.id.menuEkspor) {

        // do your work...
        return true;
    }
    return false; // no need to call super.onOptionsItemSelected(item)
}

That way, your onContextItemSelected should now be called correctly.

In a nutshell, "Menu" is the generic term for both "Context" and "Options" menu. Make sure you pay attention to the naming of the methods.

5 comments:

  1. Thank you so much.
    This was driving me bananas.

    ReplyDelete
  2. Didn't work for me. I don't have an options menu, and registerForContextMenu was called. Still it never gets called. Any other ideas?
    Justin

    ReplyDelete
  3. Wow, I'm new to android development and this was driving me crazy. Thanks a million!

    ReplyDelete