Aller au contenu principal

Spring Animation Example - Animation driven by SpringForce

Spring Animation is a powerful tool for creating animations in Android applications. It allows developers to create animations that have a natural and realistic feel, mimicking the behavior of real-world objects. In this article, we will take a deep dive into Spring Animation in Android and explore its features, benefits, and implementation.

What is Spring Animation?

Spring Animation is a type of animation that uses a spring force to create a realistic and natural movement. It is a physics-based animation that simulates the behavior of a spring, which is a flexible object that can stretch and bounce back to its original position. The Spring Animation library in Android provides a set of classes and methods that allow developers to create spring animations easily.

Features and Benefits of Spring Animation

Spring Animation offers several features and benefits that make it a popular choice for creating animations in Android applications. Some of these features and benefits include:

  • Realistic and natural movement: Spring Animation creates animations that mimic the behavior of real-world objects, making them look more natural and realistic.

  • Configurable animation parameters: Developers can customize various parameters of the animation, such as the stiffness, damping ratio, and initial velocity, to create the desired effect.

  • Smooth and fluid animation: Spring Animation creates animations that are smooth and fluid, without any jarring movements or sudden stops.

  • Performance optimization: Spring Animation is optimized for performance, ensuring that animations run smoothly on all devices.

Implementation of Spring Animation in Android

To implement Spring Animation in an Android application, the first step is to add the Spring Animation library to the project. This can be done by adding the following dependency to the app build.gradle file:

dependencies {
implementation "com.android.support:spring-animation:28.0.0"
}

Once the library is added, the next step is to create an instance of the SpringAnimation class. This can be done by passing the target view and the animation property to animate as arguments. For example, the following code creates a SpringAnimation object that animates the translationX property of a view:

val springAnimation = SpringAnimation(view, DynamicAnimation.TRANSLATION_X)

After creating the SpringAnimation object, the next step is to configure its parameters. This can be done by calling the setSpring method and passing the desired stiffness, damping ratio, and initial velocity values as arguments. For example, the following code sets the stiffness and damping ratio values for the SpringAnimation object:

springAnimation.spring.apply {
stiffness = SpringForce.STIFFNESS_VERY_LOW
dampingRatio = SpringForce.DAMPING_RATIO_HIGH_BOUNCY
}

Once the SpringAnimation object is configured, the next step is to start the animation. This can be done by calling the start method on the SpringAnimation object. For example, the following code starts the SpringAnimation object:

springAnimation.start()

Additionally, developers can also listen for animation events by adding a SpringListener to the SpringAnimation object. For example, the following code adds a SpringListener to the SpringAnimation object:

springAnimation.addEndListener { _, _, _, _ ->
// Animation ended
}

What is SpringForce?

Spring Force defines the characteristics of the spring being used in the animation.

By configuring the stiffness and damping ratio, callers can create a spring with the look and feel suits their use case. Stiffness corresponds to the spring constant. The stiffer the spring is, the harder it is to stretch it, the faster it undergoes dampening.

What is Dynamic Animation?

This class is the base class of physics-based animations.

It manages the animation's lifecycle such as start() and cancel(). This base class also handles the common setup for all the subclass animations. For example, DynamicAnimation supports adding DynamicAnimation.OnAnimationEndListener and DynamicAnimation.OnAnimationUpdateListener so that the important animation events can be observed through the callbacks. The start conditions for any subclass of DynamicAnimation can be set using setStartValue(float) and setStartVelocity(float).

You can read more here

Example

Here is a demo image:

Kotlin Android Spring Animation Example

Step 1: Create Project

Start by creating an empty Android Studio project.

Step 2: Dependencies

In your app/build.gradle add the dynamic animation dependency as shown below:

    implementation "androidx.dynamicanimation:dynamicanimation:$supportVer"

Create Splash Activity

Create a file called SplashActivity.kt.

Start by adding imports including the SpringAnimation and SpringForce:

import android.animation.Animator
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.DisplayMetrics
import android.view.animation.DecelerateInterpolator
import androidx.dynamicanimation.animation.DynamicAnimation
import androidx.dynamicanimation.animation.SpringAnimation
import androidx.dynamicanimation.animation.SpringForce
import kotlinx.android.synthetic.main.activity_splash.*

Extend the AppCompatActivity:

class SplashActivity : AppCompatActivity() {

Declare a SpringForce:

    private lateinit var springForce: SpringForce

Override the onCreate() function:

    override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)

We will do our animation inside the Handler().postDelayed callback:

        Handler().postDelayed({

Instantiate the SpringForce passing in a Float:

            springForce = SpringForce(0f)

Set the pivotX and pivotY properties:

            relative_layout.pivotX = 0f
relative_layout.pivotY = 0f

Instantiate a SpringAnimation then apply the dampingRation and stiffness:

            val springAnim = SpringAnimation(relative_layout, DynamicAnimation.ROTATION).apply {
springForce.dampingRatio = SpringForce.DAMPING_RATIO_HIGH_BOUNCY
springForce.stiffness = SpringForce.STIFFNESS_VERY_LOW
}

Then set the spring property of the SpringAnimation as a SpringForce:

            springAnim.spring = springForce

Set the start value:

            springAnim.setStartValue(80f)

Attach an end listener:

            springAnim.addEndListener { _, _, _, _ ->
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
val height = displayMetrics.heightPixels.toFloat()
val width = displayMetrics.widthPixels
relative_layout.animate()
.setStartDelay(1)
.translationXBy(width.toFloat() / 2)
.translationYBy(height)
.setListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(p0: Animator?) {

}

override fun onAnimationEnd(p0: Animator?) {
val intent = Intent(applicationContext, MainActivity::class.java)
finish()
startActivity(intent)
overridePendingTransition(0, 0)
}

override fun onAnimationCancel(p0: Animator?) {

}

override fun onAnimationStart(p0: Animator?) {

}

})
.setInterpolator(DecelerateInterpolator(1f))
.start()
}
springAnim.start()
}, 4000)
}
}

Here is the full code:

SplashActivity.kt

import android.animation.Animator
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.DisplayMetrics
import android.view.animation.DecelerateInterpolator
import androidx.dynamicanimation.animation.DynamicAnimation
import androidx.dynamicanimation.animation.SpringAnimation
import androidx.dynamicanimation.animation.SpringForce
import kotlinx.android.synthetic.main.activity_splash.*

class SplashActivity : AppCompatActivity() {

private lateinit var springForce: SpringForce

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
Handler().postDelayed({
//do stuff
//Like your Background calls and all
springForce = SpringForce(0f)
relative_layout.pivotX = 0f
relative_layout.pivotY = 0f
val springAnim = SpringAnimation(relative_layout, DynamicAnimation.ROTATION).apply {
springForce.dampingRatio = SpringForce.DAMPING_RATIO_HIGH_BOUNCY
springForce.stiffness = SpringForce.STIFFNESS_VERY_LOW
}
springAnim.spring = springForce
springAnim.setStartValue(80f)
springAnim.addEndListener { _, _, _, _ ->
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
val height = displayMetrics.heightPixels.toFloat()
val width = displayMetrics.widthPixels
relative_layout.animate()
.setStartDelay(1)
.translationXBy(width.toFloat() / 2)
.translationYBy(height)
.setListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(p0: Animator?) {

}

override fun onAnimationEnd(p0: Animator?) {
val intent = Intent(applicationContext, MainActivity::class.java)
finish()
startActivity(intent)
overridePendingTransition(0, 0)
}

override fun onAnimationCancel(p0: Animator?) {

}

override fun onAnimationStart(p0: Animator?) {

}

})
.setInterpolator(DecelerateInterpolator(1f))
.start()
}
springAnim.start()
}, 4000)
}
}

Create MainActivity

Here is our MainActivity

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolBar)
}
}

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

NumberLink
1.Download Example
2.Follow code author
3.Code: Apache 2.0 License

Conclusion

In conclusion, Spring Animation is a powerful tool for creating animations in Android applications. It offers several features and benefits, including realistic and natural movement, configurable animation parameters, smooth and fluid animation, and performance optimization. Implementing Spring Animation in an Android application is easy and straightforward, requiring only a few lines of code.