Search code examples
androidanimationandroid-animationandroid-viewobjectanimator

Click on view during animation doesn't react


I have a simple animation:

<rotate android:fromDegrees="0"
    android:toDegrees="180"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="4"
    android:repeatMode="reverse"
    android:duration="1000"
    android:interpolator="@android:anim/linear_interpolator" />

<translate
    android:duration="2000"
    android:fromXDelta="10%p"
    android:toXDelta="90%p"
    android:repeatCount="1"
    android:repeatMode="reverse"
    android:fillAfter="true"/>

and I run it on an ImageView. I have an onclick event setup on the ImageView:

    imgCorrect1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        Log.d(TAG, "explode ");
        }
    });

Here is how I start the animation:

Animation anim = AnimationUtils.loadAnimation(this, R.anim.rottrans);
imgCorrect1.startAnimation(Anim1);

The problem is that while the animation is going, the onclick doesn't get called while the animation is running if I tap on the image while it's animating.

I have tried to search on this issue, but the posts are all to animate an ImageView -when- the onclick is called, not the opposite.

I hope I have been clear here in the description. I have tried to provide all of the relevant code to explain the issue.


Solution

  • You are using Animation API, which animates the matrix of the view. Thus you see a ghost of the original view being animated, whereas the view still is positioned in the original place.

    Instead, use Animator API. Here's how it may look like:

    
            ImageView imageView = ...;
    
            ObjectAnimator rotate = ObjectAnimator.ofFloat(imageView, View.ROTATION, 0, 180);
            rotate.setRepeatCount(4);
            rotate.setRepeatMode(ValueAnimator.REVERSE);
            rotate.setDuration(1000);
            rotate.setInterpolator(new LinearInterpolator());
    
            ObjectAnimator translate = ObjectAnimator.ofFloat(imageView, View.TRANSLATION_X, 0, 100);
            translate.setRepeatCount(1);
            translate.setRepeatMode(ValueAnimator.REVERSE);
            translate.setDuration(2000);
    
            AnimatorSet set = new AnimatorSet();
    
            // Play either sequentially or together
            set.playSequentially(rotate, translate);
            // set.playTogether(rotate, translate);
    
            set.start();