如何检测视图触摸外部拖动



我正在尝试使用onTouch方法对imageView点击反馈进行编码。我的代码用于在按下时缩放imageView(MotionEvet.ACTION_DOWN),并在用户停止按下时返回到其正常大小(MotionEvet.ACTION_UP)。但我无法编码的是当用户将手指从imageView中拖出来时的动作。

我看到了一个解决方案,在switch语句的开头告诉使用MotionEvent.ACTION_CANCEL,但这对我不起作用

我的代码是下一个:

public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        switch (action) {
        case MotionEvent.ACTION_CANCEL:
        clickOutTransformation(ico);
        return true;
        case MotionEvent.ACTION_UP:
        clickOutTransformation(ico);
         switch (i) {
            case 1:
            fondoApp.setBackgroundResource(R.drawable.back_blue_bubbles_lite);
            i++;
            break;
            case 2:
            fondoApp.setBackgroundResource(R.drawable.back_espectrum);
            i++;
            break;
            case 3:
            fondoApp.setBackgroundResource(R.drawable.back_black_and_violet);
            i++;
            break;
            case 4:
            fondoApp.setBackgroundResource(R.drawable.back_green);
            i++;
            break;
            case 5:
            fondoApp.setBackgroundResource(R.drawable.back_blur_blue_ed);
            i = 1;
            break;
            default:
            break;
            }
            return true;
            case MotionEvent.ACTION_DOWN:
            clickInTransformation(ico);
            return true;
            default:
            break;
            }
             return false;
            }

您可以通过以下解决方案获得它:

private Rect rect;    // Variable rect to hold the bounds of the view
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_UP:
            if (!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) {
                // User moved outside bounds
            }
            break;
        case MotionEvent.ACTION_DOWN:
            rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
            break;
    }
    return false;
}

使用if case:MotionEvent.ACTION_DOWN进行缩放,使用case MotionEvent_ACTION_UP:缩小到正常大小。。。

ACTION_DOWN在您触摸屏幕时触发,ACTION_UP在您将手指从视图中移开时触发

最新更新