androidtouch-eventandroid-handlerlong-presspostdelayed

Detecting long presses in Android


I'm trying to detect a long press in Android. GestureDetector is deprecated, so I was trying to use Handlers. But handler isn't recognizing postDelayed or removeCallbacks. It Cannot resolve method for either.

    final Handler handler = new Handler() {
        @Override
        public void publish(LogRecord record) {

        }

        @Override
        public void flush() {

        }

        @Override
        public void close() throws SecurityException {

        }
    };

    Runnable longPressed = new Runnable() {
        @Override
        public void run() {
            Log.d("run", "long pressed");
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch(event.getAction()){
            case MotionEvent.ACTION_DOWN:
                handler.postDelayed(longPressed, 500);
                break;
            case MotionEvent.ACTION_MOVE:
                handler.removeCallbacks(longPressed);
                break;
            case MotionEvent.ACTION_UP:
                handler.removeCallbacks(longPressed);
                break;
        }

        return super.onTouchEvent(event);
    }
}

Solution

  • GestureDetector is deprecated is not exactly true.
    Only the ones Not including Context as constructor parameter are deprecated. Others with context work fine.

    final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
        public void onLongPress(MotionEvent e) {
            Log.e("", "Longpress detected");
        }
    });
    
    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    };