Physics-Based Animations: SpringAnimation and FlingAnimation

Animation in Android
A recent tool for making animation in android is physics-based animation. It is a great tool, which helps to make objects move physically plausible without overhead like a physical engine in simple animations and consists of two main classes   SpringAnimation and FlingAnimation.

SpringAnimation
By SpringAnimation, we can make our View move like a spring with specified damping, stiffness and final position. To play such animation we must firstly add a proper library which based on our implementation (our other library versions). Here the following dependency to build.gradle(Module: app) has been added

implementation 'com.android.support:support-dynamic-animation:28.0.0'

Then we can initiate an instance of SpringAnimation like below

// Create an animation to animate view's X property,
// set the rest position of the default spring to 0,
// and start the animation with a starting velocity
// of 500 (pixel/s).
final SpringAnimation anim =
    new SpringAnimation(view, DynamicAnimation.X, 0)
        .setStartVelocity(500);
anim.start();

for more details please refer to spring-animation.

Example 1:
Step 1: Create a new project with empty template. The complete dependencies for our tiny project is shown below.

dependencies {
  implementation fileTree(dir: 'libs', include: ['*.jar'])
  implementation 'com.android.support:appcompat-v7:28.0.0'
  implementation 'com.android.support:recyclerview-v7:28.0.0'
  implementation 'com.android.support:design:28.0.0'
  implementation 'com.android.support:support-v4:28.0.0'
  implementation 'com.android.support:
          support-dynamic-animation:28.0.0'
}

Also we set compileSdkVersion and targetSdkVersion version to be 28.

Step 2: The activity_main.xml file is as follows.


Step 3: In the MainActivity.java we initiate the animation and start it.


The result is something like this.



FlingAnimation
Fling animation is an animation that continues an initial momentum (most often from gesture velocity) and gradually slows down. The fling animation will come to a stop when the velocity of the animation is below the threshold derived from setMinimumVisibleChange(float), or when the value of the animation has gone beyond the min or max value defined via setMinValue(float) or setMaxValue(float). It is recommended to restrict the fling animation with min and/or max value, such that the animation can end when it goes beyond screen bounds, thus preserving CPU cycles and resources. Refer to fling animation for more details.

Example 2:
Please create a new project with empty template. The dependencies are exactly those for SpringAnimation.
Step 1: Edit the activity_main.xml something like Example 1.
Step 2: Edit the MainActivity.java as below.


Then the result is something like this.


Comments