Animations are crucial in providing a smooth and engaging experience for the users. Jetpack Compose provides an extensive list of APIs that can be used to implement different animation in an app. Many Jetpack Compose animation APIs can be used as composable functions like other layout and ui elements.
AnimatedVisibilitycomposable animates the appearance and dissapearane of elements. By default, the enter transition is fading in and expanding, and the exit transition is fading out and shrinking. The transition can be customized by specifying
Transitions can be combined using a
+operator in between
AnimatedVisibility, direct or indirect children, can use the
animateEnterExitmodifier to specify a different animation behavior for each child. The visual effect for each child is a combonation of the animation specified in the
AnimatedVisibilitycomposable and the child's own animation.
visible = visible,
enter = fadeIn(),
exit = fadeOut()
// Fade in/out the background and the foreground.
// Box is a child of AnimatedVisibility
// Slide in/out the inner box.
enter = slideInVertically(),
exit = slideOutVertically()
.sizeIn(minWidth = 256.dp, minHeight = 64.dp)
If each child wants its own distinct animation, AnimatedVisibility can apply no animations by specifying
ExitTransition.Nonein the AnimatedVisibility composable.
animate*AsStatefunctions are the easiest to animate a single value. The function takes in an end value, and the API starts the animation from the current value to the end value.
val alpha: Float by animateFloatAsState(if (enabled) 1f else 0.5f)
//alpha is the opacity of the box
.graphicsLayer(alpha = alpha)
// changes the opacity of a red rectangle between 1f to 0.5f
Jetpack Compose provides
IntSize. Other data types can be supported by providing a
animateValueAsStatethat takes a generic type.
Most animation APIs allow developers to cusomize the animation by an optional
AnimationSpecparameter. Dependent on the animation type, the
AnimationSpecwill also be different.