Search code examples
androidanimationimageviewzoomingscale

ImageView zoom in, zoom out infinite animation and onAnimationRepeat issue


I would like to build a zoom in and out animation for my ImageView, I set up a listener and set the animation RepeatCount to infinite.

First I start with a zoom in effect, then in the onAnimationRepeat method I create the zoom out part where using a boolean I would like to restart the whole effect starting to zoom in again. But after the first time the onAnimationRepeat is not called again, in turn the animation is repeating but it is stuck at the zoom out part.

What am I missing?

//image animation
        Animation anim = new ScaleAnimation(1.0f, 1.1f, 1.0f, 1.1f);
        anim.setInterpolator(new LinearInterpolator());
        anim.setRepeatCount(Animation.INFINITE);
        anim.setDuration(10000);
        zoomIn = true;

        // Start animating the image
        final ImageView splash = (ImageView) findViewById(R.id.imageView);
        splash.startAnimation(anim);

        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                if(zoomIn) {
                    Log.w("", "we zoom out, and zoomIn is: " + zoomIn);
                    Animation anim = new ScaleAnimation(1.1f, 1f, 1.1f, 1f);
                    anim.setInterpolator(new LinearInterpolator());
                    anim.setRepeatCount(Animation.INFINITE);
                    anim.setDuration(10000);
                    splash.startAnimation(anim);
                    zoomIn = false;

                } else if(!zoomIn) {
                    Log.w("", "we zoom in, and zoomIn is: " + zoomIn);
                    Animation anim = new ScaleAnimation(1.0f, 1.1f, 1.0f, 1.1f);
                    anim.setInterpolator(new LinearInterpolator());
                    anim.setRepeatCount(Animation.INFINITE);
                    anim.setDuration(10000);
                    splash.startAnimation(anim);
                    zoomIn = true;
                }


            }
        });


    }

Solution

  • Just switch to ObjectAnimator and use the following:

    ObjectAnimator scaleX = ObjectAnimator.ofFloat(btnSubscribe, "scaleX", 0.9f, 1.1f);
    ObjectAnimator scaleY = ObjectAnimator.ofFloat(btnSubscribe, "scaleY", 0.9f, 1.1f);
    
    scaleX.setRepeatCount(ObjectAnimator.INFINITE);
    scaleX.setRepeatMode(ObjectAnimator.REVERSE);
    
    scaleY.setRepeatCount(ObjectAnimator.INFINITE);
    scaleY.setRepeatMode(ObjectAnimator.REVERSE);
    
    AnimatorSet scaleAnim = new AnimatorSet();
    scaleAnim.setDuration(1000);
    scaleAnim.play(scaleX).with(scaleY);
    
    scaleAnim.start();