android – 如何在ACTION_MOVE之后让我的视图停止听取触摸事件?
作者:互联网
我有一个按钮,我按下按钮动画.我希望它在超出某个阈值之后快速恢复到“正常”状态.
我在ACTION_DOWN上创建了一个视图边界的矩形,并检查它是否在ACTION_MOVE的触摸区域之外.我成功地检测到了“越界”的触摸,但我无法让视图停止听触摸.这就像它忽略了我的animateToNormal()方法.
我已经尝试将布尔返回值更改为true而不是false,这没有帮助.我也尝试在ACTION_MOVE情况下删除触摸侦听器(设置为null),但我需要重新连接以继续听触摸.我想我可以在添加它之前添加一个任意延迟,但这似乎是一个可怕的黑客.
我正在4.2设备(LG G2)上进行测试.
private static class AnimationOnTouchListener implements View.OnTouchListener {
private Rect rect;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch(motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
rect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
animatePressed();
return false;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// back to normal state
animateBackToNormal();
return false;
case MotionEvent.ACTION_MOVE:
if(!rect.contains(view.getLeft() + (int) motionEvent.getX(), view.getTop() + (int) motionEvent.getY())){
d(TAG, "out of bounds");
animateBackToNormal();
// STOP LISTENING TO MY TOUCH EVENTS!
} else {
d(TAG, "in bounds");
}
return false;
default:
return true;
}
}
解决方法:
为什么你只是不继续听,而是设置一个声明来忽略运动事件?
像这样的东西:
private static class AnimationOnTouchListener implements View.OnTouchListener {
private Rect rect;
private boolean ignore = false;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(ignore && motionEvent.getAction()!=MotionEvent.ACTION_UP)
return false;
switch(motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
rect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
animatePressed();
return false;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// back to normal state
animateBackToNormal();
// IMPORTANT - touch down won't work if this isn't there.
ignore = false;
return false;
case MotionEvent.ACTION_MOVE:
if(!rect.contains(view.getLeft() + (int) motionEvent.getX(), view.getTop() + (int) motionEvent.getY())){
d(TAG, "out of bounds");
animateBackToNormal();
// STOP LISTENING TO MY TOUCH EVENTS!
ignore = true;
} else {
d(TAG, "in bounds");
}
return false;
default:
return true;
}
}
标签:android,ontouchlistener,android-animation 来源: https://codeday.me/bug/20190728/1563843.html