Android Translate Animation Progress Callback

Viewed 642

I am using a Translate animation (borrowed from here) as follows:

TranslateAnimation a = new TranslateAnimation(
Animation.ABSOLUTE,200, Animation.ABSOLUTE,200,
Animation.ABSOLUTE,200, Animation.ABSOLUTE,200);
a.setDuration(1000);
a.setFillAfter(true);
animationSet.addAnimation(a);
myView.startAnimation(a);

Is there any callback that can give me the current position of myView? I would like to perform an action depending on myView's position while the animation is in progress.

2 Answers

New solutions are available now as part of Spring Physics in android.

You can make use of DynamicAnimation.OnAnimationUpdateListener interface.

Implementors of this interface can add themselves as update listeners to a DynamicAnimation instance to receive callbacks on every animation frame.

Here is a quick code in kotlin to get started

// Setting up a spring animation to animate the view1 and view2 translationX and translationY properties
val (anim1X, anim1Y) = findViewById<View>(R.id.view1).let { view1 ->
    SpringAnimation(view1, DynamicAnimation.TRANSLATION_X) to
            SpringAnimation(view1, DynamicAnimation.TRANSLATION_Y)
}
val (anim2X, anim2Y) = findViewById<View>(R.id.view2).let { view2 ->
    SpringAnimation(view2, DynamicAnimation.TRANSLATION_X) to
            SpringAnimation(view2, DynamicAnimation.TRANSLATION_Y)
}

// Registering the update listener
anim1X.addUpdateListener { _, value, _ ->
    // Overriding the method to notify view2 about the change in the view1’s property.
    anim2X.animateToFinalPosition(value)
}
// same for Y position
anim1Y.addUpdateListener { _, value, _ -> anim2Y.animateToFinalPosition(value)

}

You can listen to per-frame update of the animating view and animate/update other views accordingly.

Related