If the animation state is INITIAL, the slideValue equals 90.dp. And on stateFINAL our slideValue will be 0.dp.
The next part is most important, it defines how our animation will work. We use a tween animation type which accepts the next parameters:
durationMillis — The animation duration in millis
delayMillis — The amount of time that animation starts after
easing — The easing curve that will be used to interpolate between start and end
Also, Jetpack Compose provides many types of animation, you can read them there https://developer.android.com/reference/kotlin/androidx/compose/animation/core/TransitionSpec
Now it’s time to connect our animation to UI
In our list item view looks like
@Composable fun ItemCardView(index : Int) {val listItemAnimationDefinition = remember(index) { ListItemAnimationDefinition(300) } val listItemTransition = transition( definition = listItemAnimationDefinition.definition, initState = ListItemAnimationState.INITIAL, toState = ListItemAnimationState.FINAL, ) Card( modifier = Modifier .height(200.dp) .fillMaxWidth() .absoluteOffset(x = listItemTransition[listItemAnimationDefinition.slideValue]) ) { Text( text = "I'm a card from Jetpack Compose", textAlign = TextAlign.Center ) } }
There we declaring our animation that will run from INITIAL state to FINAL state, and pass definition which indicates how our animation must work.
Also as we know recomposition happens many times in Jetpack Compose. So we will use remember to store our animation and use it when recomposition happens.
To animate our Card we will absoluteOffset function in our Modifier and pass to x argument our animated value
.absoluteOffset(x =listItemTransition[listItemAnimationDefinition.slideValue])
And that’s all. Let’s run our application and see the result.
And that’s all. Let’s run our application and see the result.
Additional
You can also add alpha animation using FloatPropKey.
Just add new variable
val alphaValue = FloatPropKey(label = "alpha")
Sets alpha value at INITIAL and FINAL state
state(ListItemAnimationState.INITIAL) { this[slideValue] = 90.dp this[alphaValue] = 0.0f } state(ListItemAnimationState.FINAL) { this[slideValue] = 90.dp this[alphaValue] = 0.0f }
Then, in transitionDefinition add following code
alphaValue using tween( durationMillis = 400, delayMillis = delay )
Don’t forget add alpha modifier to your UI
.alpha(listItemTransition[listItemAnimationDefinition.slideValue])
Conclusion
Today we learned how to create and use animations in Jetpack Compose. Animations in Jetpack Compose is impressive because it allows creating beautiful UI animations very easily. I hope it will be useful for you.
Feel free to follow me on Twitter, also don’t hesitate to ask questions related to this.
Thanks for reading, and see you later!