首页 > 解决方案 > 布局上的 onTouch 事件每次点击只注册一个触摸

问题描述

我有以下问题:我创建了一个扩展 ConstraintLayout 的新类,并且我正在覆盖 onTouchEvent 函数来为布局设置动画。

@Override
    public boolean onTouchEvent(MotionEvent event) {

        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                ObjectAnimator scaleDownX = ObjectAnimator.ofFloat(this, "scaleX", 0.85f);
                ObjectAnimator scaleDownY = ObjectAnimator.ofFloat(this, "scaleY", 0.85f);
                scaleDownX.setDuration(100);
                scaleDownY.setDuration(100);

                AnimatorSet scaleDown = new AnimatorSet();
                scaleDown.play(scaleDownX).with(scaleDownY);

                scaleDown.start();
                break;

            case MotionEvent.ACTION_CANCEL:
                Log.d("arne", "CANCEL");
                // Beide Cases lösen das Event aus
                // ACTION_CANCEL minimiert den Button auch, wenn man den Knopf nicht loslässt, sondern weg wischt
            case MotionEvent.ACTION_UP:
                ObjectAnimator scaleUpX = ObjectAnimator.ofFloat(this, "scaleX", 1f);
                ObjectAnimator scaleUpY = ObjectAnimator.ofFloat(this, "scaleY", 1f);
                scaleUpX.setDuration(100);
                scaleUpY.setDuration(100);

                AnimatorSet scaleUp = new AnimatorSet();
                scaleUp.play(scaleUpX).with(scaleUpY);

                scaleUp.start();
                break;
        }

        return super.onTouchEvent(event);
    }

这对按钮完美无缺,如果我按住按钮,事件会在一秒钟内触发多次。

但是在 ConstraintLayout 上它只触发一次,就像 onClick 事件一样。

这在我的理解中有点奇怪。

你有这个问题的解决方案吗?

标签: javaandroidandroid-layoutbutton

解决方案


好的,我终于找到了解决方案。

你只需要设置你的布局可点击。

android:clickable="true"

推荐阅读