Blog Infos
Implementing Bounce Animation with Animatable
Purpose
In reference to an earlier blog post, I got questions about how to implement a small feature to bounce the front layer of the BackdropScaffold as an introductory wizard. Here is a short tutorial for it.
Approach & Implementation
Let us run down the thinking process.
- The bouncing is essentially about animating the offset value of the front-layer of the BackdropScaffold. Getting the offset State from BackdropScaffoldState would allow us to manipulate the offset value. In order to write to the state, we need to cast the offset State into MutableState.
- In order to animate the offset value, we want to use a lower-level animation API called Animatable as the container to drive the value. The suspect function Animatable.animateTo() would require a coroutine environment in order to update its value to change continuously over time. So LaunchEffect is used here.
- Within coroutine, apply Animatable<>.animateTo() to lift up to a new offset with tween animation spec.
- Perform drop-down animation in the same coroutine, so it would follow the lift-up animation subsequently.
- Finally, drive the BackdropScaffoldState.offset State with the Animatable value
Here is the snippet with comments:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val backdropState = rememberBackdropScaffoldState(Revealed) | |
var offset by (backdropState.offset as MutableState) | |
// Optional conditions: ex. should-bounce flag, data-loading finished, etc. | |
if (backdropState.isRevealed) { | |
// remember the original offset position to go back to | |
val revealedOffset = remember { backdropState.offset.value } | |
// value holder Animatable for the actual offset | |
val offsetAnimatable = remember { Animatable(revealedOffset) } | |
LaunchedEffect(Unit) { | |
// lift up by 150 pixels with tween animation spec | |
offsetAnimatable.animateTo( | |
targetValue = revealedOffset - 150, | |
animationSpec = tween(800) | |
) | |
// drop down back to original offset with spring animation spec | |
offsetAnimatable.animateTo( | |
targetValue = revealedOffset, | |
animationSpec = spring( | |
dampingRatio = 0.4f, | |
stiffness = Spring.StiffnessLow | |
) | |
) | |
} | |
// drive offset mutableState with Animatable values | |
offset = offsetAnimatable.value | |
} |
Job Offers
Final Thought
Animatable comes in handy for many custom animation situations. Hope the tutorial helps.
Regarding what animation API to use, here is a helpful resource.
This article was originally published on proandroiddev.com on October 18, 2022