Search code examples
androidandroid-custom-viewtouch-eventontouchlistener

ACTION_CANCEL not fired


I implemented a customView to add a little animation when a view is touched and relieved. When the user click on this view, i launch a small animation of 80ms which shrink the view.

When the finger is up, the same animation is played (reverse effect). The visual effect is great, and it works properly as long as the user don't leave the view by moving his finger.

Therefore, i just can't get any call to ACTION_CANCEL when the finger leave the view area, which is needed in my case to play the animation back.

ACTION_UP, ACTION_MOVE and ACTION_DOWN are properly called, but never ACTION_CANCEL

Here's my code:

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

Solution

  • Check this answer: https://stackoverflow.com/a/20160587/1576319

    It explains in detail why ACTION_CANCEL is not fired up in API>16 and provides a quick workaround.