Animations in depth
Why it matters
- Animations run every frame. Reading an animated value in the wrong phase makes Compose recompose 60 or more times a second, which is a common source of jank on Android.
- Compose has several animation APIs, and senior interviews ask which one fits:
animate*AsState,updateTransition,AnimatedVisibility,AnimatedContent,AnimatableorrememberInfiniteTransition. - Gesture-driven UI (drag to dismiss, swipe, fling) needs
Animatable, because it can snap to the finger and continue with the gesture's velocity. - Small details decide whether an exit animation plays at all, whether two properties stay in sync, and whether an interrupted animation jumps or flows.
The simple explanation
animate*AsStateis a thermostat: you set the target, it moves there smoothly, and if you change the target halfway it turns around without a jump.updateTransitionis a conductor: one state change, many properties moving together.Animatableis driving by hand: you decide when to snap, when to animate, and with what starting speed.rememberInfiniteTransitionis a metronome: it keeps going while it is in the composition.
How do animations work in Jetpack Compose? An animation API holds a value in Compose state and updates it once per frame until it reaches its target. Whatever reads that state gets updated. If the read happens in a composable body, that scope recomposes every frame; if it happens inside a lambda modifier such as graphicsLayer { }, offset { } or drawBehind { }, only layout or draw re-runs. All Compose animations are interruptible: a new target starts from the current value and velocity.
| API | Use it for | Notes |
|---|---|---|
animateFloatAsState, animateDpAsState, animateColorAsState | One value following a target | Simplest; returns State<T> |
updateTransition(targetState) | Several values driven by one state | Keeps properties in sync; visible in Android Studio's Animation Preview |
AnimatedVisibility | Enter and exit of content | Keeps content composed until the exit animation ends |
AnimatedContent | Swapping content when a target changes | transitionSpec returns a ContentTransform (enter togetherWith exit) |
Modifier.animateContentSize() | Smooth size change of one element | Animates layout size |
Animatable | Gestures, sequences, imperative control | animateTo, snapTo, animateDecay; suspend functions in a coroutine |
rememberInfiniteTransition | Looping effects such as pulses and shimmers | Runs while it is in the composition |
Specs decide the motion: spring() (the default for most APIs, physics-based, keeps velocity on interruption), tween(durationMillis, easing) for fixed timing, keyframes { } for set points, and infiniteRepeatable for loops.
Shared element transitions use SharedTransitionLayout with Modifier.sharedElement() or sharedBounds() inside AnimatedVisibility, AnimatedContent or Navigation Compose destinations. These APIs started as experimental, so check whether your Compose version still needs @OptIn(ExperimentalSharedTransitionApi::class).
Notes
- Read animated values inside
graphicsLayer { },offset { }ordrawBehind { }when you can. Reading ingraphicsLayerskips composition and layout and only redraws. Modifier.alpha(value)orModifier.offset(x.dp)with a parameter reads the value in composition. Use the lambda versions for values that change every frame.- Animating
Modifier.size()orpadding()changes layout every frame. If the change is purely visual,graphicsLayer { scaleX = ...; scaleY = ... }is cheaper, but it does not move neighbours. animate*AsStatehandles interruption well: changing the target mid-way continues from the current value and velocity. UseAnimatablewhen you need to snap to a gesture, run steps in sequence, or start with a fling velocity.Animatable.animateTosuspends until the animation ends and cancels any running animation on the sameAnimatable. Run it fromrememberCoroutineScope()in callbacks or fromLaunchedEffect.- After a drag, pass the velocity from
VelocityTrackertoanimateTo(target, initialVelocity = v)or useanimateDecay(v, splineBasedDecay(density))for a fling. - Do not wrap
AnimatedVisibilityinif (visible). Whenvisibleturns false the whole block leaves the composition at once and the exit animation never plays. updateTransitionkeeps several properties on one timeline and shows them together in Android Studio's Animation Preview. Give every animation alabelso it is easy to find there.- Avoid hand-written loops with
delay(16)to animate a value. Animation APIs follow the real frame clock and the device's animator duration scale, which tests can also control.
Code example
A card that expands on tap. updateTransition drives the corner radius and elevation-like scale together, AnimatedVisibility shows details, and a drag handle uses Animatable to follow the finger and spring back.
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.layout.offset
import kotlin.math.roundToInt
import kotlinx.coroutines.launch
@Composable
fun ExpandableCard(title: String, details: String) {
var expanded by remember { mutableStateOf(false) }
// One state, two properties on the same timeline
val transition = updateTransition(targetState = expanded, label = "card")
val corner by transition.animateDp(label = "corner") { if (it) 4.dp else 16.dp }
val scale by transition.animateFloat(label = "scale") { if (it) 1.03f else 1f }
// Imperative control for the drag
val dragX = remember { Animatable(0f) }
val scope = rememberCoroutineScope()
Column(
Modifier
.fillMaxWidth()
.padding(16.dp)
.offset { IntOffset(dragX.value.roundToInt(), 0) } // read in layout
.graphicsLayer { scaleX = scale; scaleY = scale } // read in draw
.background(Color(0xFFE8EAF6), RoundedCornerShape(corner))
.pointerInput(Unit) {
detectHorizontalDragGestures(
onHorizontalDrag = { _, dx -> scope.launch { dragX.snapTo(dragX.value + dx) } },
onDragEnd = { scope.launch { dragX.animateTo(0f, spring()) } },
)
}
.clickable { expanded = !expanded }
.padding(16.dp)
) {
Text(title)
AnimatedVisibility(
visible = expanded,
enter = fadeIn() + expandVertically(),
exit = fadeOut() + shrinkVertically(),
) {
Text(details, Modifier.padding(top = 8.dp))
}
}
}cornerandscalecome from oneTransition, so they start and finish together and appear as one entry in Animation Preview.dragXis read insideoffset { }andscaleinsidegraphicsLayer { }, so dragging and scaling do not recomposeExpandableCard.corneris read in composition becauseRoundedCornerShapetakes a value; that is fine for a short transition, not for a per-frame loop.- During the drag,
snapTofollows the finger with no animation. On release,animateTo(0f, spring())springs back. A real swipe-to-dismiss would pass the release velocity asinitialVelocity. AnimatedVisibilitykeeps the details composed while the exit animation runs, then removes them.
Run the idea in plain Kotlin
A model of an interruptible linear tween, frame by frame. Halfway through, the target changes and the animation continues from the current value instead of jumping.
class LinearAnimation(var value: Float) {
private var start = value
private var target = value
private var frame = 0
private var frames = 0
fun animateTo(newTarget: Float, durationFrames: Int) {
start = value // interruption: begin from where we are now
target = newTarget
frame = 0
frames = durationFrames
}
fun onFrame(): Boolean {
if (frame >= frames) return false
frame++
val fraction = frame.toFloat() / frames
value = start + (target - start) * fraction
return true
}
}
fun main() {
val alpha = LinearAnimation(0f)
alpha.animateTo(1f, durationFrames = 4)
var n = 0
while (alpha.onFrame()) {
n++
println("frame " + n + ": " + alpha.value)
if (n == 2) {
println("user taps again -> new target 0.0")
alpha.animateTo(0f, durationFrames = 2)
}
}
println("finished at " + alpha.value + " after " + n + " frames")
}Expected output:
frame 1: 0.25
frame 2: 0.5
user taps again -> new target 0.0
frame 3: 0.25
frame 4: 0.0
finished at 0.0 after 4 frames
In production
- A list showed a pulsing "new" badge on some rows, implemented with
animateDpAsStatefeedingModifier.size(badgeSize). - Layout Inspector showed those rows recomposing on every frame, and the size change re-measured the row and its neighbours each frame too.
- On lower-end devices scrolling stuttered whenever badges were visible.
- The badge kept a fixed layout size and animated
scaleXandscaleYinsidegraphicsLayer { }, so only drawing re-ran per frame. - The pulse moved to
rememberInfiniteTransitioninside the badge composable, so it exists only while a badge is on screen. - Recomposition counts for the rows stopped increasing during the pulse, and a Macrobenchmark scroll test showed fewer slow frames.
- A snackbar-like banner was written as
if (showBanner) { AnimatedVisibility(visible = showBanner) { Banner() } }. - The enter animation worked, but on dismiss the banner vanished instantly.
- When
showBannerbecame false, theifremovedAnimatedVisibilityfrom the composition in the same frame, so it had no chance to run the exit.
- The
ifwas removed:AnimatedVisibility(visible = showBanner)now stays in the composition and handles both directions. - For content that must be cleaned up after the exit (such as clearing the message), the team used
MutableTransitionStateand reacted whenisIdlewas true andcurrentStatewas false. - A UI test with the main clock paused advances time and asserts the banner is still shown halfway through the exit.
Common mistakes
- Reading per-frame values in composition.
Modifier.alpha(animatedAlpha)orModifier.offset(x = animatedX)recompose every frame. UsegraphicsLayer { alpha = ... }oroffset { IntOffset(...) }. - Animating layout properties for a visual effect. Animating
sizeorpaddingre-measures every frame. UsegraphicsLayerscale or translation when neighbours do not need to move. - Wrapping
AnimatedVisibilityin anif. The exit animation cannot run. Pass the condition asvisibleand keep the composable in the tree. - Creating
Animatablewithoutremember. A newAnimatablewith the initial value is created on each recomposition, so the animation keeps restarting. - Hand-rolled animation loops. A
LaunchedEffectthat changes state and callsdelay(16)ignores the real frame timing and the system animation scale. Use the animation APIs. - Using
animate*AsStatefor gestures. It cannot follow a finger withsnapToor start from a fling velocity. UseAnimatablefor drag and fling. - Ignoring Animation Preview. Unlabelled animations are hard to find there. Pass
labeltoanimate*AsStateand transition children.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between animateFloatAsState and Animatable?”
“How do you keep animations from causing jank in Compose?”
“What happens if you use Modifier.offset(x = animatedX) instead of Modifier.offset { }?”
“When do you use updateTransition instead of several animate*AsState calls?”
Quiz
You animate alpha with Modifier.graphicsLayer { alpha = animatedAlpha }. What re-runs on each frame?
Which API fits a drag-to-dismiss card that must follow the finger and then fling with the release velocity?
Why does if (visible) { AnimatedVisibility(visible) { ... } } never play its exit animation?
What does updateTransition give you over separate animate*AsState calls?
0 of 4 answered
Mini task
Build a pulse that does not recompose (20 min)
- Create the composable. Write
@Composable fun PulseDot(color: Color)that draws a 24 dp circle. - Animate it. Use
rememberInfiniteTransition(label = "pulse")andanimateFloat(1f, 1.3f, infiniteRepeatable(tween(600), RepeatMode.Reverse), label = "scale"). - Defer the read. Apply the scale with
Modifier.graphicsLayer { scaleX = scale; scaleY = scale }and draw the circle withdrawBehind { drawCircle(color) }. - Show it conditionally. In a parent, show
PulseDotonly whenisLiveis true, usingif (isLive) PulseDot(...)so the infinite animation stops when it is hidden. - Verify. Open Layout Inspector with recomposition counts. Watch
PulseDotfor ten seconds. - Break it on purpose. Change the scale to
Modifier.scale(scale)and watch the count again, then revert.
Done condition: with the graphicsLayer version, PulseDot's recomposition count stays the same while it pulses, and with Modifier.scale(scale) it rises continuously.