2

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.

androidnoob
  • 345
  • 2
  • 17

2 Answers2

3

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 
            }
        });
MSpeed
  • 8,153
  • 7
  • 49
  • 61
  • Thanks a lot for the answer :) . Though does it essentially mean that such overhead can't be avoided? – androidnoob Aug 16 '17 at 11:54
  • Yeah, I'm assuming it's because there could be dropped frames and such if the phone is doing a lot of heavy lifting. Depending on what you want to do at each iteration there could be other solutions. – MSpeed Aug 16 '17 at 14:09
0

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.

Arpit J.
  • 1,108
  • 12
  • 20