其他分享
首页 > 其他分享> > android – 从onDown()返回false的含义

android – 从onDown()返回false的含义

作者:互联网

根据android training,如果你扩展GestureDetector.SimpleOnGestureListener,并从onDown(…)返回false,而不是GestureDetector.SimpleOnGestureListener的其他方法永远不会被调用:

Whether or not you use GestureDetector.OnGestureListener, it’s best practice to implement an onDown() method that returns true. This is because all gestures begin with an onDown() message. If you return false from onDown(), as GestureDetector.SimpleOnGestureListener does by default, the system assumes that you want to ignore the rest of the gesture, and the other methods of GestureDetector.OnGestureListener never get called. This has the potential to cause unexpected problems in your app. The only time you should return false from onDown() is if you truly want to ignore an entire gesture.

但是,在我的简单测试中,调用了onScroll(…).

public void onCreate(Bundle savedInstanceState) {
    mDetector = new GestureDetectorCompat(this, MyGestureListener);
}


public boolean onTouchEvent(MotionEvent event) { 
    mDetector.onTouchEvent(event);
    return true;
}


class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
    private boolean scrollEvent;

    @Override
    public boolean onDown (MotionEvent event) {
        Log.v("GESTURE", "onDown ");
        return false;
    }

    @Override
    public boolean onScroll (MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        Log.v("GESTURE", "onScroll");
        return true;
    }

另一个类似的问题是下一个定义,同样来自同一个Android培训页面:

a return value of true from the individual on methods indicates that you have handled the touch event. A return value of false passes events down through the view stack until the touch has been successfully handled.

这与先前的报价如何解决?

解决方法:

The only time you should return false from onDown() is if you truly want to ignore an entire gesture.

这几乎说明了一切.

关键是onDown(…)方法接收一个MotionEvent作为参数,你可以选择在onDown(…)方法中分析MotionEvent,如果它不是你想要处理的东西那么你返回false .

MotionEvent包含许多详细信息,其中包括手势开始的位置(例如) – 如果它在您想要处理的区域之外,则返回false,否则返回true.

如果从onDown(…)返回true,则将调用其他方法.这些方法中的每一个都可以选择分析和处理传递给它们的各种参数.如果您在任何这些方法中处理事件并且不想要任何进一步的操作,那么从这些方法返回true,否则将调用其他方法(可能在超类中,具体取决于您的代码实现).

手势很复杂,涉及向上和向上的动作以及任何方向的动作.允许选项拒绝手势(通过在onDown(…)中返回false)会使事情变得更加通用.

编辑:在某些情况下,可能会出现屏幕上有多个视图的情况.传递给onDown(…)的MotionEvent将包含有关手势开始位置的信息.如果您不希望屏幕的某些区域对手势做出反应,那么当您检查手势的开始位置时,您将返回false.

标签:gesture,android
来源: https://codeday.me/bug/20190830/1771319.html