skip to content

In Compose, how does AnimatedContent's transitionSpec with togetherWith and SizeTransform swap content, and when are Crossfade or animateContentSize enough?

level: middleimportance: should knowfreq 58%

answer

  1. target state in, content per state
  2. always use the lambda's own parameter
  3. ContentTransform: enter togetherWith exit
  4. SizeTransform animates the container
  5. Crossfade fades only; animateContentSize resizes one node

basics

~10 s

AnimatedContent keeps the outgoing and incoming content composed while a ContentTransform runs: an EnterTransition togetherWith an ExitTransition, plus a SizeTransform that animates the container's size. Crossfade only fades; animateContentSize only resizes one composable.

solid answer

~40 s

`AnimatedContent(targetState = price) { targetPrice -> ... }` composes the content for both the old and the new state during a change, and the content lambda **must** use its parameter, because the container looks content up by that value. `transitionSpec` returns a `ContentTransform`, built as `enter togetherWith exit`, and can compare `initialState` with `targetState`, for example to slide up for a higher price and down for a lower one. `using SizeTransform(...)` controls the container's size animation and clipping; `null` turns size animation off. The default is a delayed `fadeIn` plus `scaleIn(0.92f)` together with a quick `fadeOut`, using a `SizeTransform`. Choose `Crossfade` when a plain fade between states is enough (its default spec is `tween()`), and `Modifier.animateContentSize()` when a single composable keeps its identity but changes size.

code

kotlin · 15 lines
kotlin
AnimatedContent(
    targetState = price,
    transitionSpec = {
        if (targetState > initialState) {
            slideInVertically { height -> height } + fadeIn() togetherWith
                slideOutVertically { height -> -height } + fadeOut()
        } else {
            slideInVertically { height -> -height } + fadeIn() togetherWith
                slideOutVertically { height -> height } + fadeOut()
        }.using(SizeTransform(clip = false))
    },
    label = "price",
) { targetPrice ->
    Text(text = "Price: $targetPrice")
}

go deeper

for a junior

Recall that AnimatedContent swaps content for a target state and that the content lambda must use its parameter.

for a middle

Build a ContentTransform with togetherWith, branch on initialState and targetState, and explain what SizeTransform's clip and null do.

for a senior

Use contentKey to avoid spurious transitions and zIndex for overlap. Choose Crossfade or animateContentSize when AnimatedContent is more machinery than the change needs.

for a principal

Pick one content-change pattern per component type so screens behave alike, and document which state changes deserve a transform at all.

## What AnimatedContent does **`AnimatedContent`** animates a change of **which content is shown** for a target state. You pass `targetState` and a content lambda that maps a state to UI. When the target changes, the container looks up the content for both the **initial** (outgoing) and **target** (incoming) state. Both stay composed while a **`ContentTransform`** animates one out and the other in. When the transform finishes, the outgoing content is disposed. That lookup is why the KDoc marks one rule as important: **the content lambda must use its own parameter**. In `AnimatedContent(targetState = price) { targetPrice -> Text("$targetPrice") }`, reading the outer `price` instead of `targetPrice` makes the outgoing copy render the new price too, so the old value never visibly leaves. ## Building a ContentTransform `transitionSpec` is a lambda on `AnimatedContentTransitionScope<S>`. That scope exposes `initialState` and `targetState`, so the spec can depend on the direction of the change. For the flower shop's price label: - price goes up: `slideInVertically { h -> h } + fadeIn() togetherWith slideOutVertically { h -> -h } + fadeOut()` - price goes down: the mirror image, so the numbers roll the other way. Key pieces: 1. **`togetherWith`** joins an `EnterTransition` for the target content with an `ExitTransition` for the initial content. It replaced the older infix `with` in Compose 1.5; in 1.12 `with` is still present but deprecated and experimental. 2. **`using`** attaches a **`SizeTransform`**. `SizeTransform(clip = true)` with a spring (`Spring.StiffnessMediumLow`) is the default. Its `sizeAnimationSpec` lambda receives `initialSize` and `targetSize`, so you can, for instance, expand width first and height second with `keyframes`. `clip = false` lets sliding content draw outside the container during the change. Passing `null` turns size animation off. 3. **`slideIntoContainer` and `slideOutOfContainer`** are scope helpers that compute the slide distance from the container and content sizes. 4. **`ContentTransform.targetContentZIndex`** decides draw order during the overlap. Content with a higher z-index draws on top, and among equal indexes the incoming content is placed last, so it draws on top. Give the incoming content a lower `targetContentZIndex` when the outgoing content should stay in front, for example a card sliding away over the new one. The default `transitionSpec` is a `fadeIn(tween(220, delayMillis = 90))` plus `scaleIn(initialScale = 0.92f, ...)`, `togetherWith` a `fadeOut(tween(90))`, with the default `SizeTransform`. `contentAlignment` defaults to `Alignment.TopStart`. ## contentKey: animate only meaningful changes `contentKey` maps a state to a key. A transition runs only when the **key** changes. If the target is an order object that changes often, keying on its step (`{ it.step }`) avoids re-animating on every unrelated field change. ## Choosing between the three APIs | Need | API | What it animates | |---|---|---| | Different content per state, with slide, fade, scale and size | `AnimatedContent` | enter, exit and container size together | | Simple fade between states | `Crossfade` | alpha only, `tween()` by default | | Same composable, its own size changes | `Modifier.animateContentSize()` | that node's measured size | - **`Crossfade(targetState, animationSpec = tween())`** fades the old content out and the new one in. It has no slide, scale or `SizeTransform`, so a size difference between the two contents is not animated. - **`Modifier.animateContentSize()`** animates a composable's own size when its content grows or shrinks, for example a bouquet description expanding to show more text. It clips to its bounds, defaults to a spring with `Spring.StiffnessMediumLow`, and offers a `finishedListener(initialValue, targetValue)`. The documentation stresses that **order matters**: place it before size modifiers such as `size` or `defaultMinSize` so the animated size reaches layout. ## Hoisting into a shared Transition `AnimatedContent` also exists as an extension on `Transition`: `transition.AnimatedContent { state -> ... }`. Its target comes from the parent transition, so the content swap runs as a child of the same `updateTransition` that drives, say, the card's elevation and border colour. The parent then reports completion only after the swap finishes too. Use this when a content change is one part of a larger state change and the parts must start and finish together. ## Common mistakes - Reading outer state instead of the lambda parameter, so the outgoing content shows new data. - Expecting `AnimatedVisibility` to swap content; it only shows or hides one piece. - Forgetting `SizeTransform(clip = false)` when slide-ins look cut off at the container edge. - Using `AnimatedContent` for a pure resize where `animateContentSize()` would do. Inside the content lambda, the `AnimatedContentScope` is also an `AnimatedVisibilityScope`. It offers `Modifier.animateEnterExit` and `transition` for per-child motion, just as `AnimatedVisibility` does.

  • The order screen's state object changes on every keystroke, but the step panel should animate only when the checkout step changes; how?
    Pass `contentKey = { it.step }` to `AnimatedContent`. Transitions run only when the key changes, so edits that keep the same step update the current content in place, without a transform.
  • When would you set SizeTransform to null?
    When the container should take the target size at once, without animating it, for example when the parent animates its own bounds or the two contents are the same size. `using(null)` turns size animation off, while the enter and exit transitions still run.
  • Why might animateContentSize appear to do nothing?
    Usually because of modifier order. If a fixed `size` or `height` modifier comes before it, the size that `animateContentSize` sees never changes. The documentation advises placing it before size modifiers so the animated size reaches layout.

  • The content lambda can read the outer state variable instead of its parameter.
  • Crossfade animates the size difference between its two contents.
  • SizeTransform(clip = false) turns off the size animation.
  • with is the current way to combine enter and exit transitions.
  • AnimatedVisibility is the API for swapping one content for another.