Context menu

ContextMenu is a new component in LWUIT for Series 40, available for full touch and touch and type devices. It is used for item specific commands, typically in lists. Although the LWUIT ContextMenu allows using any gesture or other interaction for opening the menu, long tap is the recommended way to launch the context menu in Series 40 touch phones.

Currently there is no ContextMenu implementation for Series 40 non-touch devices.

Figure: ContextMenu component

Example of showing ContextMenu with LONG_TAP gesture

Using the class is simple: an array of commands with the static show method is given to ContextMenu class and it will show a menu.

public class Midlet extends MIDlet{

    public void startApp() {
        Display.init(this);
        Form f = new Form("context menu");
        String[] items = new String[13];
        for(int i = 1; i < items.length+1; i++) {
            items[i-1] = "item" + (i);
        }
        DefaultListModel model = new DefaultListModel(items);
        final List list = new List(model);
        
        
        f.addComponent(list);
        GestureHandler longtap = new GestureHandler(GestureHandler.GESTURE_LONG_PRESS) {

            public void gestureAction(GestureEvent ge) {
                int x = ge.getStartX();
                int y = ge.getStartY();
                if (list.contains(x, y)) {
                    Display.getInstance().callSerially(new Runnable() {
                        public void run() {
                            int selected = list.getSelectedIndex();
                            Command []cmds = new Command[selected+1];
                            for(int i = 0; i < cmds.length; i++) {
                                cmds[i] = new Command("item" + (i+1) +" " + (selected+1));
                            }
                            Command selectedContextCmd = ContextMenu.show(cmds, list);
                            System.out.println("selected:" + selectedContextCmd);
                        }
                    });
                }
            }
        };
        GestureHandler.setFormGestureHandler(f, longtap);
        f.show();
    }
    
    public void pauseApp() {
    }
    
    public void destroyApp(boolean unconditional) {
    }
}

Note that you can use any method you want to show the menu, but pay attention to the fact that the example code calls Display.callSerially for showing the context menu. This is because the context menu is based on dialog and is a modal dialog, which will cause the calling thread to freeze until dialog is dismissed. In the case of using gesture event, the method is called from the platform event handler and we do not want to freeze that, so we need to move the processing back to the LWUIT UI thread.