其他分享
首页 > 其他分享> > 安卓 – 长按GestureDetector也会点击

安卓 – 长按GestureDetector也会点击

作者:互联网

我尝试从这个问题实现代码:Detecting a long press with Android,但它总是检测到长按,即使我只是点击它.我的代码如下(我扩展了ImageView,因为其中包含更多代码,与此问题无关):

public class EbsImageView extends ImageView  {
    final GestureDetector gestureDetector = new GestureDetector(this.getContext(), new GestureDetector.SimpleOnGestureListener() {
        public void onLongPress(MotionEvent e) {
            Log.e("", "Longpress detected");
        }
    public boolean onSingleTapUP(MotionEvent e) {
        Log.e("", "Press detected");

            // don't consume, we want the long press to fire if it was a 
            // long press
        return false;
        }
    });

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }
}

解决方法:

您需要覆盖onDown并使其返回true.以下代码对我有用:

class SimpleGestureListener extends GestureDetector.SimpleOnGestureListener {

    @Override
    public boolean onDown(MotionEvent event) {
      // triggers first for both single tap and long press
      return true;
    }

    @Override
    public boolean onSingleTapUp(MotionEvent event) {
      // triggers after onDown only for single tap
      return true;
    }

    @Override
    public void onLongPress(MotionEvent event) {
      // triggers after onDown only for long press
      super.onLongPress(event);
    }
}

标签:gesture,android
来源: https://codeday.me/bug/20191006/1860347.html