在 Android 中检测长按

Detecting long presses in Android

我正在尝试检测 Android 中的长按。 GestureDetector 已弃用,所以我尝试使用 Handlers。但是 handler 无法识别 postDelayedremoveCallbacks。它 Cannot resolve method 两者都适用。

    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);
    }
}

View.OnLongClickListener.html呢?


你会得到类似的东西:

yourView.setOnLongClickListener(new View.OnLongClickListener() {
  @Override public boolean onLongClick(View v) {
    // Toast it out!
    return false;
  }
});

GestureDetector 已弃用 不完全正确。
只有 不包括 Context 作为构造函数参数的参数被弃用。其他有上下文的工作正常。

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);
};

如果不想使用手势检测器,可以使用 Handler。

//Declare this flag globally
boolean goneFlag = false;
//Put this into the class
final Handler handler = new Handler(); 
Runnable mLongPressed = new Runnable() { 
    public void run() { 
        goneFlag = true;
        //Code for long click
    }   
};

//onTouch code
@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {    
    case MotionEvent.ACTION_DOWN:
        handler.postDelayed(mLongPressed, 1000);

        break;
    case MotionEvent.ACTION_UP:
        handler.removeCallbacks(mLongPressed);
        if(Math.abs(event.getRawX() - initialTouchX) <= 2 && !goneFlag) {
            //Code for single click
            return false;
        }
        break;
    case MotionEvent.ACTION_MOVE:
        handler.removeCallbacks(mLongPressed);

        break;
    }
    return true;
}