6

I have the following code (Android project in Scala):

val animator = new ValueAnimator
animator.setFloatValues(0f, 100f)
animator.setDuration(20000L)
animator.addUpdateListener(this) // prints current value to console
animator.start

override def onTouch(v: View, event: MotionEvent) = {
  animator.setFloatValues(100f, 0f)
  animator.setCurrentPlayTime(0)

  if (!animator.isRunning) animator.start
  true
}

If I touch the screen while animator is running then it correctly starts working backwards (since I've swapped the values). But if I touch the screen after it is finished then nothing happens, it does not start over.

Question is can I reuse this animator somehow and make it work again for given values after it has been stopped?

src091
  • 2,807
  • 7
  • 44
  • 74
  • 1
    No you cannot. I just checked it . I too wanted to reuse it in my application. So use clone to get a new instance and then set target views to each. – Napolean Jun 18 '15 at 08:03

2 Answers2

4

You can reuse animator in the following way:

...
animator.end();
animator.setFloatValues(...);
animator.start();
...

You can also use animator.cancel() instead of animator.end() and pass the last value from the last animation to the new animation as a starting float. For instance, if the last animated value is 50, you can call animator.setFloatValues(50, 0f) so your animations will look connected.

Considering the accepted answer states it's impossible, I would like to mention that the described approach is used in Touch Circle app when users make tap with two fingers. BTW, it's a very nice effect when object trembles a little bit - use it as you wish, code exerpt is below:

void shapeTremble(long delay) {
    if (null == animatorTremble) {
        ValueAnimator animator = new ValueAnimator();
        animator.setDuration(850).setInterpolator(new AccelerateDecelerateInterpolator());
        animator.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                setCircleScale((Float) valueAnimator.getAnimatedValue(), true);
            }
        });
        animatorTremble = animator;
    } else {
        animatorTremble.cancel();
    }
    animatorTremble.setFloatValues(circleScale, 0.85f, 1.05f, 0.95f, 1.025f, 1.0f);
    animatorTremble.setStartDelay(delay);
    animatorTremble.start();
}
GregoryK
  • 3,011
  • 1
  • 27
  • 26
1

You cannot reuse an animation.

You need to reset() and reinitialize an animation object by calling the initialize() method before using the same object again. This is similar to instantiating a new animation object.

Anupam KR
  • 484
  • 4
  • 5