1

尝试通过从 GestureDetector 借用代码来实现长按,我得到了一个最小示例,当 onTouchEvent() 返回 true 时,它​​不会在 GestureHandler 中接收消息。返回 false 时,确实会传递消息,但事件处理结束并且长按不会被取消。

有没有办法让这个代码与 onTouchEvent() 返回 true 一起工作?

public class OverlayView extends View  {
    private static final int LONG_PRESS = 1;
    private Handler handler;
    private static final String TAG = OverlayView.class.getName();
    private class GestureHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case LONG_PRESS:
                dispatchLongPress();
                break;

            default:
                throw new RuntimeException("Unknown message " + msg);
            }
        }
    }

    public OverlayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        handler = new GestureHandler();
    }

    private void dispatchLongPress() {
        Toast.makeText(getContext(), "Long Press", Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        Log.d(TAG, e.toString());
        switch (e.getAction()) {
        case MotionEvent.ACTION_DOWN:
            handler.removeMessages(LONG_PRESS);          
            handler.sendEmptyMessageAtTime(LONG_PRESS, e.getDownTime() + 1000);
            break;
        case MotionEvent.ACTION_MOVE:
            handler.removeMessages(LONG_PRESS);
            break;
        case MotionEvent.ACTION_UP:
            handler.removeMessages(LONG_PRESS);
            break;
        default:
            break;
        }

        return true;
    }
}
4

1 回答 1

1

即使您的手非常稳定,您也可能会创建一个ACTION_MOVE事件:

case MotionEvent.ACTION_MOVE:
    handler.removeMessages(LONG_PRESS);
    break;

您的手指只会移动几个像素,但这足以消除您的长按回调。

Android uses a couple static variables label ___SLOP and calculates the distance between the first ACTION_DOWN event and the current event. Once the MotionEvent has traveled beyond the slop threshold, only then does it cancel the callback. I recommend using the same approach.

于 2012-12-10T18:00:19.203 回答