AlanArBras AlanArBras - 3 months ago 11
Android Question

How to start an additional animation on a View without stopping its running animation?

I want an ImageView to be rotating all the time and make it bounce when the user clicks on it.

I have both animations but I can't start the bouncing animation without stopping the rotating one.


I don't want to start both animations at once.


Here is what I have: Animation_Fail.

AnimationSet doesn't seem to be what I need as the second animation has to start on click while the first one is running.


Does anybody know how to do this?

Answer

Thank you pskink, it works fine! Here is the working code:

private ImageView rotating_image;
private AnimatorSet bounceAnimatorSet;
private ObjectAnimator rotationAnimator;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    rotating_image = (ImageView) findViewById(R.id.rotating_image);
    if (rotating_image != null)
        rotating_image.setOnClickListener(this);
    setRotation();
    rotationAnimator.start();
    setBounceAnimators();
    ...
}

private void setRotation(){
    rotationAnimator = ObjectAnimator.ofFloat(rotating_image, "rotation",0,360);
    rotationAnimator.setDuration(4000);
    rotationAnimator.setRepeatCount(ValueAnimator.INFINITE);
    rotationAnimator.setRepeatMode(ValueAnimator.RESTART);
    rotationAnimator.setInterpolator(new LinearInterpolator());
}


private void setBounceAnimators(){
    bounceAnimatorSet = new AnimatorSet();
    ObjectAnimator enlargeX = ObjectAnimator.ofFloat(rotating_image, "scaleX",1,1.5f);
    enlargeX.setDuration(800);
    enlargeX.setInterpolator(new LinearInterpolator());

    ObjectAnimator enlargeY = ObjectAnimator.ofFloat(rotating_image, "scaleY",1,1.5f);
    enlargeY.setDuration(800);
    enlargeY.setInterpolator(new LinearInterpolator());

    ObjectAnimator bounceX = ObjectAnimator.ofFloat(rotating_image, "scaleX", 1.5f, 1);
    bounceX.setDuration(1000);
    bounceX.setInterpolator(new BounceInterpolator());

    ObjectAnimator bounceY = ObjectAnimator.ofFloat(rotating_image, "scaleY", 1.5f, 1);
    bounceY.setDuration(1000);
    bounceY.setInterpolator(new BounceInterpolator());

    bounceAnimatorSet.play(enlargeX).with(enlargeY);
    bounceAnimatorSet.play(bounceY).with(bounceX).after(enlargeY);
}