Animations in Android
  • Introduction
  • About us
  • Basic animations
  • ConstraintLayout: Core concepts
  • I like to move it, move it!
  • Step 1
  • Step 2
  • Step 2: Solution
  • Step 3
  • Step 3: Solution
  • Step 4
  • Step 4: Solution
  • Step 5
  • Step 5: Solution
  • Step 6
  • Step 7
  • Step 7: Solution
  • Step 8
  • Step 8: Solution
  • MotionLayout
  • Party time!
  • Shared element transition
  • Adding a RecyclerView
  • Activity transitions
  • Adding a second Activity
  • Adding the shared element transition
  • You made it!
  • VectorDrawable
  • VectorDrawable: Solution
  • Using the VectorDrawable
  • RecyclerView item animation & self-contained MotionScene
  • Creating a self-contained MotionScene
  • Creating a self-contained MotionScene : Solution
  • Adding animations in the RecyclerView items: Step 1
  • Adding animations in the RecyclerView items: Step 2
  • RecyclerView animations step 2: Solution
  • Physic based animations
  • Implement a spring animation
  • Spring animation: Solution
  • The finish line!
Powered by GitBook
On this page

Implement a spring animation

PreviousPhysic based animationsNextSpring animation: Solution

Last updated 6 years ago

We are going to apply the spring animation to our avatar view in the Detail activity.

First we need to set the stiffness and the damping ratio of our animation. To do so we are going to create a SpringForce object.

In the SpringForce object we are going to set the stiffness level to STIFFNESS_LOW and the damping ratio to DAMPING_RATIO_HIGH_BOUNCY. The final position should be 0f since we don't want our view to translate at the end of the animation, but instead to return to the position it was before the animation.

Once you're done, we will create 2 SpringAnimation objects: one with DynamicAnimation.TRANSLATION_X and the other one with DynamicAnimation.TRANSLATION_Y. To both of them we need to apply the SpringForce object we just created as their spring.

Finally, we need a onTouchListener for getting coordinates of our view and for applying our animations.

DetailActivity.kt
var dX = 0f
var dY = 0f

root.setOnTouchListener { view, motionEvent ->
    when (motionEvent?.action) {
        MotionEvent.ACTION_DOWN -> {
            dX = motionEvent.rawX
            dY = motionEvent.rawY
        }

        MotionEvent.ACTION_MOVE -> {
            val newX = motionEvent.rawX - dX
            val newY = motionEvent.rawY - dY
            iv_avatar.animate().translationX(newX).translationY(newY).duration = 0
            springAnimationX.animateToFinalPosition(0f)
            springAnimationY.animateToFinalPosition(0f)
        }
    }
    true
}
Different level of stiffnesses
Different levels of damping ratios