OnTouchListener intercept when touch goes outside view

核能气质少年 提交于 2019-12-23 01:38:09

问题


I have an ImageView that represent a button, and a relative OnTouchListener for change image inside it (for simulate pression on it) and launch a task:

@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;
}

Now this two events are not sufficient for my scope. I would that, if user keep finger pressed on ImageView AND swipe outside it, task inside ACTION_UP will not executed. How can i do it?


回答1:


Here is a View.OnTouchListener that you can use to see if MotionEvent.ACTION_UP was sent while the user had his/her finger outside of the view:

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;
        }
    }
};


来源:https://stackoverflow.com/questions/25446855/ontouchlistener-intercept-when-touch-goes-outside-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!