问题
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