ACTION_CANCEL 未触发

sch*_*sss 2 android android-custom-view ontouchlistener touch-event

我实现了一个 customView 来在视图被触摸和释放时添加一些动画。当用户单击此视图时,我会启动一个 80 毫秒的小动画,从而缩小视图。

当手指抬起时,播放相同的动画(反向效果)。视觉效果很棒,只要用户不移动手指离开视图就可以正常工作。

因此,当手指离开视图区域时,我无法调用 ACTION_CANCEL ,而在我的情况下,这是播放动画所必需的。

ACTION_UP、ACTION_MOVE 和 ACTION_DOWN 被正确调用,但从未 ACTION_CANCEL

这是我的代码:

@Override
public boolean onTouchEvent(MotionEvent event) {
    super.onTouchEvent(event);
    switch (event.getAction()) {
        case MotionEvent.ACTION_CANCEL: {
            Animation anim = new ScaleAnimation(0.9f, 1f, 0.9f, 1f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            anim.setDuration(Utils.ANIM_CLICK_LENGHT);
            anim.setFillAfter(true);
            anim.setFillBefore(true);
            startAnimation(anim);
            break;
        }
        case MotionEvent.ACTION_DOWN: {
            Animation anim = new ScaleAnimation(1f, 0.9f, 1f, 0.9f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            anim.setDuration(Utils.ANIM_CLICK_LENGHT);
            anim.setFillAfter(true);
            anim.setFillBefore(true);
            startAnimation(anim);
            break;
        }
        case MotionEvent.ACTION_UP: {
            Animation anim = new ScaleAnimation(0.9f, 1f, 0.9f, 1f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            anim.setDuration(Utils.ANIM_CLICK_LENGHT);
            anim.setFillAfter(true);
            anim.setFillBefore(true);
            startAnimation(anim);
            break;
        }
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

Tos*_*she 5

检查这个答案:/sf/answers/1411241121/

它详细解释了为什么 ACTION_CANCEL 在 API>16 中未触发,并提供了快速解决方法。