当触摸超出视图范围时,OnTouchListener会拦截 [英] OnTouchListener intercept when touch goes outside view
问题描述
我有一个ImageView,它代表一个按钮,以及一个相对的OnTouchListener,用于在其中更改图像(用于模拟按压)并启动任务:
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;
}
现在,这两个事件对于我的范围还不够.我希望,如果用户在ImageView上按住手指并在其外部滑动,则ACTION_UP内的任务将不会执行. 我该怎么办?
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?
推荐答案
这是一个View.OnTouchListener
,您可以使用它来查看MotionEvent.ACTION_UP
是在用户的手指不在视图之外时发送的:>
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;
}
}
};
这篇关于当触摸超出视图范围时,OnTouchListener会拦截的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!