在Android中检测长按

时间:2018-03-08 20:19:03

标签: android ontouchevent android-handler long-press postdelayed

我试图在Android中检测长按。 GestureDetector已被弃用,因此我尝试使用Handler。但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);
    }
}

3 个答案:

答案 0 :(得分:1)

View.OnLongClickListener.html怎么样?

你会得到类似的东西:

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

答案 1 :(得分:0)

不推荐使用GestureDetector 并非完全正确 仅弃用不包括上下文作为构造函数参数的那些。其他有背景的人工作正常

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

答案 2 :(得分:0)

如果您不想使用Gesture Detector,则可以使用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;
}