Android Physics-based Animation

Physics-based animation relies on the laws of physics to manifest a high degree of realism in animation. In our day-to-day life, when a change occurs, it comes with a physical transition that is natural for us to recognize. Similarly, animations that are more natural-looking, uninterrupted, and the ones that maintain momentum, are easily perceived by us.

When you are trying to develop smooth and flexible animations in Android, it is painful and it doesn’t seem right. The animations on Android are provided with fixed time and changes in animation values. It’s very challenging to try to arrange it without stopping the animation.

Now, we can solve our animation problems with physics-based APIs. You can see the difference between Non-Physics(ObjectAnimator) and Physics-based at below.

How to Use ?

We can look how to use Physics-based animations in our project. First step is always adding dependency to gradle.

compile "com.android.support:support-dynamic-animation:25.3.1"

After syncing we can start with SpringAnimation class. This class lets you create a spring animation for a view.

SpringAnimation anim = new SpringAnimation(view, SpringAnimation.TRANSLATION_X, 0);

Now we can set DampingRatio and Stiffness to our SpringAnimation object. That provides to our animation that capabilities.

anim.getSpring().setStiffness(100f);
anim.getSpring().setDampingRatio(100f);

If you want to give velocity capability your animation, you can use VelocityTracker class. The default start velocity is set to zero pixel per second.

velocityTracker.computeCurrentVelocity(1000);

There are two ways you can start a spring animation: By calling the start() or by calling the animateToFinalPosition() method. Both the methods need to be called on the main thread.

SpringAnimation anim = new SpringAnimation(circle, SpringAnimation.TRANSLATION_Y, 0);
anim.getSpring().setStiffness(getStiffness());
anim.getSpring().setDampingRatio(getDamping());
anim.setStartVelocity(velocityTracker.getYVelocity());
anim.start();

There are two methods for terminate the animation. One of them is cancel() method terminates the animation at the value where it is. Other method is canSkipToEnd(). This method skips the animation to final value and terminates it.

anim.cancel();
anim.canSkipToEnd();

Conclusion

New physics-based animation library gives us the capability of creating awesome animations. I am trying to do some interesting animations, when it is finished I will write an article about that.

If you are looking for an example with physics-based animation API. You can check Nick Butcher’s example.