当触摸进入视图外时,OnTouchListener拦截

时间:2014-08-22 12:16:48

标签: android listener android-imageview ontouchlistener

我有一个表示按钮的ImageView,以及一个用于更改图像的相对OnTouchListener(用于模拟压力)并启动任务:

@Override
public boolean onTouch(View v, MotionEvent event) {
    ImageView button = (ImageView) v;

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN: {
        //change imageview image with pressed button
        return true;

    }
    case MotionEvent.ACTION_UP: {
            //change imageview image, and do a task
            return true;
    }

    }
    return false;
}

现在这两个事件对我的范围来说还不够。我想,如果用户将手指按在ImageView上并在其外滑动,ACTION_UP内的任务将不会执行。 我该怎么办?

1 个答案:

答案 0 :(得分:0)

以下是View.OnTouchListener,您可以使用MotionEvent.ACTION_UP查看当用户的手指在视图之外时是否发送了private OnTouchListener mOnTouchListener = new View.OnTouchListener() { private Rect rect; @Override public boolean onTouch(View v, MotionEvent event) { if (v == null) return true; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom()); return true; case MotionEvent.ACTION_UP: if (rect != null && !rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) { // The motion event was outside of the view, handle this as a non-click event return true; } // The view was clicked. // TODO: do stuff return true; default: return true; } } };

{{1}}