尝试通过从 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;
}
}