【问题标题】:ACTION_CANCEL not firedACTION_CANCEL 未触发
【发布时间】:2013-10-30 04:42:30
【问题描述】:

我实现了一个 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;
}

【问题讨论】:

    标签: android android-custom-view touch-event ontouchlistener


    【解决方案1】:

    检查这个答案:https://stackoverflow.com/a/20160587/1576319

    它详细解释了为什么在 API>16 中没有启动 ACTION_CANCEL,并提供了一个快速的解决方法。

    【讨论】:

    • 完美运行,非常感谢,我已经找了很长时间:)
    【解决方案2】:

    Kotlin 答案when 情况下使用 MotionEvent.ACTION_UP 和 MotionEvent.ACTION_CANCEL 解决了这个问题:

    when (event.action) {
        MotionEvent.ACTION_DOWN -> startBrushEvent()
        MotionEvent.ACTION_MOVE -> useBrush(image as ImageView, event)
        MotionEvent.ACTION_UP,
        MotionEvent.ACTION_CANCEL ->
            stopBrushEvent()
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-26
      • 2022-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      相关资源
      最近更新 更多