Search code examples
blackberrymenucontextmenulistfieldlong-click

Blackberry: detect long click on a ListField and display menu


How do you detect a long click on a ListField component?

Do you override its navigationClick(int status, int time) and fumble with its time argument (how?) or is there some builtin method for detecting long clicks?

And more importantly - how do you display the menu (the one in the middle of the screen) once you detected such a click?

The background is that on short clicks I'd like to let the user edit the selected item. And on long clicks I'd like to display a menu in the middle of the screen to offer secondary tasks: delete item, change item display order, etc.

Below is my current test code - src\mypackage\MyList.java:

enter image description here

package mypackage;

import java.util.*;
import net.rim.device.api.collection.*;
import net.rim.device.api.collection.util.*; 
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.decor.*;
import net.rim.device.api.util.*;

public class MyList extends UiApplication {
    public static void main(String args[]) {
        MyList app = new MyList();
        app.enterEventDispatcher();
    }

    public MyList() {
        pushScreen(new MyScreen());
    }
} 

class MyScreen extends MainScreen {
    ObjectListField myList = new ObjectListField() {
        protected boolean navigationClick(int status, int time) {
            System.err.println("XXX status=" + status + ", index=" + getSelectedIndex());
            return true;
        }
    };

    public MyScreen() {
        setTitle("How to detect long click?");
        myList.set(new String[] { "Item 1", "Item 2", "Item 3", "Item 4", }); 
        add(myList);
    }
}

Thank you Alex


Solution

  • You can override the touchEvent method of your Field. Then do something like this:

    ObjectListField myList = new ObjectListField() {
            long touchedAt = -1;
            long HOLD_TIME = 2000; // 2 seconds or whatever you define the hold time to be
            protected boolean touchEvent(TouchEvent message) {
                if(message.getEvent() == TouchEvent.DOWN) {
                   touchedAt = System.currentTimeMillis();
                } else if(message.getEvent() == TouchEvent.UP) {
                   if(System.currentTimeMillis() - touchedAt < HOLD_TIME)
                      touchedAt = -1; // reset
                   else
                      //write logic you need for touch and hold
                }
                return true;
            }
        };
    

    Please note that this is a rough implementation just to give you an idea. I only used the time coordinate here. Your implementation will probably need to factor in the X and Y coordinates of where the user touched the screen, because if he moved his finger, then that wouldn't be a touch and hold.