androidnoob
androidnoob

Reputation: 355

Android Translate Animation Progress Callback

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.

Upvotes: 2

Views: 919

Answers (2)

Arpit J.
Arpit J.

Reputation: 1148

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.

Upvotes: 0

MSpeed
MSpeed

Reputation: 8290

Unfortunately not, but you could do something like this. Use

a.setRepeatCount(200);

and set the animation to move 1 pixel at a time

Animation.ABSOLUTE,1

then

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

            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                 // this will fire after each repetition 
            }
        });

Upvotes: 3

Related Questions