Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 104 ยท Building a Real UI

Animation in Compose

Learn Compose animation from the ground up: animate*AsState, AnimatedVisibility, updateTransition, animateContentSize, tween versus spring and gestures, with stand-ins.

Good animation explains what just happened: a card expands because you tapped it, a row slides away because you deleted it. In the old View system you wrote animators, listeners and cleanup. In Compose, animation fits the same idea as everything else: the UI is a function of state, so you do not animate a view, you animate a value that the UI reads. Change the target and Compose moves the value toward it over several frames, recomposing or redrawing as it goes.

This lesson covers the everyday animation APIs and how to choose between a time-based tween and a physics-based spring. The Compose code is read-only because it needs the Android SDK; the TryIt blocks are stand-ins that step through frames in plain Kotlin, so you can see the numbers that the real APIs compute internally. State and recomposition basics are in State and remember.

Animate a value with animate*AsState

The simplest API is a family of functions named animate*AsState (animateFloatAsState, animateDpAsState, animateColorAsState, and so on). You pass the target, and you get back a State that moves toward it:

Kotlin
// read-only example: needs the Android SDK and Compose
@Composable
fun ExpandableCard(title: String, details: String) {
    var expanded by remember { mutableStateOf(false) }
    val arrowAngle by animateFloatAsState(
        targetValue = if (expanded) 180f else 0f,
        animationSpec = tween(durationMillis = 300),
        label = "arrow",
    )

    Card(onClick = { expanded = !expanded }) {
        Row {
            Text(title)
            Icon(
                Icons.Default.KeyboardArrowDown,
                contentDescription = null,
                modifier = Modifier.rotate(arrowAngle),
            )
        }
        if (expanded) Text(details)
    }
}

When expanded flips, the target changes from 0 to 180. arrowAngle does not jump; it takes a new value each frame (0, 4.1, 11.7, ... 180), and the rotate modifier reads it. If the user taps again halfway, the animation redirects smoothly from its current value toward the new target. The label is only a name shown in tooling.

The stand-in below runs the frame loop by hand. It takes a start, an end, a duration, an easing curve, and prints the value at 60 frames per second. Easing is a function from progress (0 to 1) to a fraction (0 to 1) that makes motion feel natural.

Kotlin A tween frame stepper (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Read the rows: linear moves the same amount each frame; ease-in starts slowly and accelerates; ease-out starts fast and settles. In Compose the built-in curves are LinearEasing, FastOutSlowInEasing (the default for tween) and LinearOutSlowInEasing, or you can provide a CubicBezierEasing.

Spring or tween?

tween has a fixed duration: you choose how long. spring has no duration: you choose stiffness and damping ratio, and the motion follows a physical model, which makes it the default for most Compose animations. Its big advantage is interruptibility: if the target changes mid-flight, a spring keeps its current velocity and curves toward the new target, while a tween has to restart a timed curve from the current value.

Kotlin
// read-only example
animateDpAsState(
    targetValue = if (selected) 120.dp else 80.dp,
    animationSpec = spring(
        dampingRatio = Spring.DampingRatioMediumBouncy,
        stiffness = Spring.StiffnessLow,
    ),
)

A damping ratio of 1 means no overshoot; below 1 the value overshoots and oscillates. Stiffness controls how fast the spring pulls. Use tween when timing must be exact (a color fade that matches a 200 ms transition elsewhere), and spring for movement that responds to touch.

The second stand-in integrates a damped spring step by step, the same way a physics animation works. It prints the position at each frame and reports whether it overshot.

Kotlin A damped spring, step by step (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The bouncy spring goes past 100 and returns; the critically damped one approaches 100 from below. Real Compose uses an analytical spring solution rather than this simple integration, but the behavior is the same.

Appearing and disappearing

Animating content that enters or leaves the composition is the job of AnimatedVisibility. You pass a Boolean, and optionally enter and exit transitions that you can add together with +:

Kotlin
// read-only example
AnimatedVisibility(
    visible = showBanner,
    enter = fadeIn() + slideInVertically(),
    exit = fadeOut() + shrinkVertically(),
) {
    Banner("You are offline")
}

When visible becomes false, the content stays in the composition until its exit animation ends, then it is removed. For switching between whole screens or states, AnimatedContent(targetState = ...) animates the old content out and the new content in. For a container that simply changes size when its content changes, add Modifier.animateContentSize() and you are done; it is one of the cheapest big wins.

Several values, one state: updateTransition

When one state change drives multiple animated values (a card's color, size and elevation), animating each separately risks them going out of sync and makes the code repetitive. updateTransition gives one transition object keyed on the state; each value is animated from it:

Kotlin
// read-only example
val transition = updateTransition(targetState = selected, label = "card")
val color by transition.animateColor(label = "color") { if (it) Color.Blue else Color.Gray }
val elevation by transition.animateDp(label = "elevation") { if (it) 8.dp else 1.dp }

All of these values share one lifecycle, and tools like Android Studio's Animation Preview can inspect the whole transition.

flowchart LR
    S["state changes<br/>(expanded = true)"] --> T["target value changes"]
    T --> A["animation spec<br/>(tween or spring)"]
    A --> F["new value every frame"]
    F --> U["UI reads the value<br/>and redraws"]

State changes the target; the animation spec decides how the value travels there; the UI only ever reads the current value.

Gestures and performance

For animation that follows a finger, such as dragging a card, use Animatable with pointerInput and detectDragGestures: while dragging you call snapTo, on release you call animateTo or animateDecay with the release velocity. The draggable, swipeable-style anchoredDraggable and Modifier.offset { } APIs build on the same idea. Keep two rules in mind for smooth results:

  • Read animated values in the latest possible phase. Modifier.graphicsLayer { rotationZ = angle } or Modifier.offset { IntOffset(x, 0) } take lambdas, so the value is read during drawing or layout and the composable does not recompose on every frame.
  • Do not animate things that change layout every frame (like width) if a draw-only property (like scale or alpha) does the job.

Common mistakes

  • Animating with a plain variable. Only state-backed values trigger redraws; use animate*AsState.
  • Forgetting that tween restarts when interrupted; prefer spring for interactive motion.
  • Reading the value in the composable body when a lambda modifier would avoid recomposition on each frame.
  • Over-animating. Every animation needs a purpose; respect the system's "remove animations" setting for accessibility.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does animateFloatAsState return?

    It returns a State<Float>. When the target changes, the value moves toward it frame by frame according to the animation spec, and the UI that reads it updates.
  2. 2. Which animation spec keeps its velocity when the target changes in the middle of an animation?

    A spring is physics-based and has no fixed duration, so it carries its current velocity toward the new target. A tween restarts a timed curve.
  3. 3. When should you use updateTransition?

    A transition keyed on one target state animates multiple properties together, such as color, size and elevation, and can be inspected as a unit.
  4. 4. Why prefer Modifier.graphicsLayer { ... } with the animated value inside the lambda?

    Reading state inside the lambda defers the read to the draw phase, avoiding recomposition and layout work for each frame.

Summary

  • In Compose you animate values, not views: change the target and the value moves toward it.
  • animate*AsState is the entry point; AnimatedVisibility and AnimatedContent handle content that enters and leaves; animateContentSize handles size changes.
  • tween runs for a fixed time with an easing curve; spring is physics-based, has no duration and handles interruption gracefully.
  • updateTransition keeps several values on one state in sync.
  • For gestures use Animatable with snapTo and animateTo; read animated values in lambda modifiers to skip recomposition.
  • The TryIts here are stand-ins that compute the same frame values by hand.

Next: Adaptive Layouts and Window Size Classes