Search code examples
androidcontextmenuosmdroid

Opening a Context menu on long press for a View?


All the examples and questions I've seen regarding context menus have been where you register the context menu to a button or something similar. In my case I have a display sized View (OSMDroid map view) that has it's over long press gesture implemented that will pass in a pressed node in the map view. I want the long press to open a context menu so I can action on that node.

The issue is when I register the MapView for a context menu, the long press will fire when the view itself or a node on the view is pressed. e.g. it's registered for the view. (bad!)

If I don't register the context menu for the view, my long press will trigger fine only when a node is selected. (good!) HOWEVER I have no clue how to programmaticially display or trigger a context menu that's not registered first.

I just need to display a context menu on demand. Anyone have any suggestions? Thanks!

@Override
public void onCreate(final Bundle savedInstanceState) {
    ...
    this.mapView = (MapView) findViewById(R.id.mapview);
    this.registerForContextMenu(this.mapView); // <-- This will register the entire view for a long press context menu
    ...
}
...

class NodeGestureListener implements OnItemGestureListener<NodeOverlayItem> {
    @Override
public boolean onItemLongPress(int index, NodeOverlayItem node) {
    openContextMenu(mapView);  // <-- This won't display anything
    return false;
}
}
...

@Override 
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {  
    super.onCreateContextMenu(menu, v, menuInfo);
    getMenuInflater().inflate(R.menu.node_menu, menu);
}

Solution

  • EveryThing has it's own purpose and structure. So it is always better to use something as how it is supposed to be used. Same thing goes with the menu.

    In your case I think if you want a immediate popup after a long click event without the context menu mechanism then better use a AlertDialog.