Saturday, September 10, 2011

Android: How To Create A ContextMenu

I have a custom View in which I want to show a dynamic ContextMenu. It was hard to figure out the steps to do because most of the tutorials show only how it works with Views from the framework like the ListView.
The missing part is how my view could trigger the onCreateContextMenu() callback.

As an overview, here are the steps in pseudo code:
  1. Activity.registerForContextMenu(customView);
  2. CustomView.showContextMenu();
  3. Activity.onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
This works pretty well only the parameter menuInfo is null.
If the method is invoked by a framework class you will get a class that is derived from ContextMenu.ContextMenuInfo which holds additional information about the caller.
In the case of a ListView the class is called AdapterContextMenuInfo and holds 3 Information.

  • calling view
  • position in the list
  • id

Wouldn't it be nice to provide custom MenuInfo from your custom View? As far I havn't found a way.

The next step is to call the showContextMenu() methode from a onLongClick listener like I described in one Post before.
Unfortunately this is not realy possible under some circumstances.

If you want to start a context menu with the long click event on a custom view with your own dragging and zooming routines, it is nearly impossible.
The problem is that you have to distinguish between a finger that stays on one place and one in motion until the long click is recognized.
The only way to figure out motion or not is to cache the MotionEvent at ACTION_DOWN time and at ACTION_MOVE time. Than you have to calculate the spacial delta.
But the onLongClick event is triggered microseconds after ACTION_DOWN with no chance ever to get a ACTION_MOVE event.

No comments:

Post a Comment