Skip to content
Commitwise
Menu
Android Development

Compose layouts, modifiers and animation

Understand Compose's single-pass layout (constraints down, sizes up, placement), write custom layouts and Modifier.Node modifiers, use intrinsics and SubcomposeLayout only when needed, choose the right animation API (animate*AsState, AnimatedVisibility, AnimatedContent, updateTransition, Animatable), and animate in the draw phase so animations don't recompose every frame.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The product screen’s design has a row of cards that should all be as tall as the tallest one, a custom “ticket” shape with a notch, a price badge that bounces when the price changes, and a details panel that expands smoothly. The first version uses BoxWithConstraints inside every list item, measures text twice to find the tallest card, and animates the badge by changing a dp value in state. Scrolling drops frames, and Layout Inspector shows the badge recomposing 60 times a second.

Compose layout and animation are both built on a few rules: each child is measured once, parents pass constraints down and children report sizes up, and state read in a phase only invalidates that phase. Knowing them is the difference between custom UI that’s smooth and custom UI that’s quietly expensive.

New to some of these? Open what you need, or skip ahead.

Basics:What is a modifier?

A modifier decorates or configures a composable: Modifier.padding(16.dp).background(Color.Yellow).clickable { … }. Modifiers are applied in order, from the outside in, so padding then background leaves the padding uncolored. See view modifierView modifierA method like .padding() or .background() in SwiftUI that wraps a view in a new view with a changed look or behavior.Open in glossary →.

Basics:What is recomposition?

Recomposition is Compose running a composable function again because state it read has changed, to update the UI. It’s cheap when it happens rarely and for small parts of the screen, and expensive when it happens every frame for big ones. See recompositionRecompositionJetpack Compose running a composable function again because state it reads has changed.Open in glossary →.

Part Not started

Custom layouts and modifiers

Compose lays out the screen in a single pass, top to bottom:

  1. The parent gives each child constraints: “you can be between 0 and 360 dp wide, and up to 800 dp tall”.
  2. Each child measures itself within those constraints and reports its size.
  3. The parent places each child at an x and y.

The important rule: each child may be measured only once per layout. That’s what keeps Compose fast even with deep trees. If you need “all cards as tall as the tallest”, you can’t measure them all, find the tallest, and measure again.

Compose gives you tools for that:

Layout is a single pass: Constraints flow down, sizes flow up, then placement. Measuring a Measurable twice in one pass throws, which guarantees linear-time layout. Layout(content) { measurables, constraints -> } measures children (usually with relaxed constraints, constraints.copy(minWidth = 0)) and returns layout(width, height) { placeable.place(x, y) }; Modifier.layout { measurable, constraints -> } does the same for a single element. Intrinsic measurements (minIntrinsicHeight and friends, via IntrinsicSize.Min/Max) answer “how big would you be” without a real measure, at the cost of an extra traversal. SubcomposeLayout (behind BoxWithConstraints, LazyColumn, Scaffold) composes content during layout, when its content depends on measured sizes; it can’t skip like normal composition, so it’s expensive inside list items. For reusable behavior, write Modifier.Node modifiers (ModifierNodeElement + LayoutModifierNode/DrawModifierNode/PointerInputModifierNode): they’re allocated once and updated, comparable for skipping, unlike composed {}. CompositionLocal is for implicit, tree-scoped values (theme, density, a tracking context), not for passing dependencies that should be explicit parameters.

// All cards as tall as the tallest one, without measuring twice
@Composable
fun FeatureRow(features: List<Feature>) {
    Row(Modifier.height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
        features.forEach { feature ->
            FeatureCard(feature, Modifier.weight(1f).fillMaxHeight())
        }
    }
}

// A custom layout: a label and a price, with the price aligned to the end on the label's last baseline
@Composable
fun LabelWithPrice(label: @Composable () -> Unit, price: @Composable () -> Unit, modifier: Modifier = Modifier) {
    Layout(contents = listOf(label, price), modifier = modifier) { (labelMeasurables, priceMeasurables), constraints ->
        val pricePlaceable = priceMeasurables.first().measure(constraints.copy(minWidth = 0))
        val labelPlaceable = labelMeasurables.first().measure(
            constraints.copy(minWidth = 0, maxWidth = constraints.maxWidth - pricePlaceable.width)
        )
        val height = maxOf(labelPlaceable.height, pricePlaceable.height)
        layout(constraints.maxWidth, height) {
            labelPlaceable.place(0, 0)
            val baselineOffset = labelPlaceable[LastBaseline] - pricePlaceable[LastBaseline]
            pricePlaceable.place(constraints.maxWidth - pricePlaceable.width, baselineOffset.coerceAtLeast(0))
        }
    }
}

// A reusable modifier as a Modifier.Node: draws a dashed outline
fun Modifier.dashedBorder(color: Color, width: Dp = 1.dp) = this then DashedBorderElement(color, width)

private data class DashedBorderElement(val color: Color, val width: Dp) : ModifierNodeElement<DashedBorderNode>() {
    override fun create() = DashedBorderNode(color, width)
    override fun update(node: DashedBorderNode) {
        node.color = color
        node.width = width
        node.invalidateDraw()
    }
}

private class DashedBorderNode(var color: Color, var width: Dp) : Modifier.Node(), DrawModifierNode {
    override fun ContentDrawScope.draw() {
        drawContent()
        drawRect(color, style = Stroke(width.toPx(), pathEffect = PathEffect.dashPathEffect(floatArrayOf(12f, 8f))))
    }
}
  • IntrinsicSize.Min makes the Row as tall as its tallest card needs to be; fillMaxHeight() makes every card use that height.
  • Layout(contents = …) measures the price first, gives the label the remaining width, then places them on the same baseline. Each child is measured exactly once.
  • DashedBorderElement is a small data class: Compose compares it between recompositions, and if nothing changed, it does nothing. The Node does the drawing and lives as long as the modifier stays on the screen.
Spot the bugMeasuring twice

Tap the line with the bug.

@Composable
fun EqualColumns(content: @Composable () -> Unit) {
    Layout(content) { measurables, constraints ->
        val tallest = measurables.maxOf { it.measure(constraints).height }
        val placeables = measurables.map {
            it.measure(constraints.copy(minHeight = tallest, maxHeight = tallest))
        }
        layout(constraints.maxWidth, tallest) {
            var x = 0
            placeables.forEach { it.place(x, 0); x += it.width }
        }
    }
}

Choosing the right layout tool

NeedToolCost
Standard arrangements, wrapping chipsRow, Column, Box, FlowRow, FlowColumnLowest
Children sized to each other (equal heights)IntrinsicSize.Min/MaxOne extra intrinsic pass
A custom arrangementLayout, Modifier.layoutSame as built-ins
Content that depends on available sizeBoxWithConstraints, SubcomposeLayoutComposition during layout, no skipping
Behavior reused across many composablesModifier.NodeAllocated once, comparable

BoxWithConstraints at the screen level (choose a two-pane layout) is fine; in every list item it adds subcomposition to each item’s measure, which is visible in scroll performance. Window size classes (currentWindowAdaptiveInfo()) answer most “which layout?” questions without it.

  • Single-pass layout: constraints down, sizes up, place. Measuring a measurable twice throws.
  • Layout { measurables, constraints -> layout(w, h) { place } }, Modifier.layout; relax minWidth for children.
  • Intrinsics (IntrinsicSize.Min/Max, maxIntrinsicHeight) for size-to-siblings; extra traversal, no double measure.
  • SubcomposeLayout/BoxWithConstraints compose during layout and don’t skip: avoid in list items; prefer window size classes.
  • Modifier.Node (ModifierNodeElement + node interfaces) over composed {}; CompositionLocal for implicit tree values, not dependencies.

Check this part

  1. How many times may a custom Layout measure each child?

  2. How do you make all cards in a Row as tall as the tallest?

  3. Why is BoxWithConstraints in every LazyColumn item a scroll performance risk?

  4. Why prefer Modifier.Node over composed {} for custom modifiers?

Compose lays out in one pass: a parent gives each child constraints (min and max width and height), measures each child exactly once, then places them. Custom arrangements use the Layout composable. Use intrinsics (IntrinsicSize.Min) for 'as tall as the tallest' rows, and SubcomposeLayout or BoxWithConstraints only when content depends on available size, since they compose during layout. Write reusable modifiers with Modifier.Node, not composed {}.

Part Not started

Animation

Compose has a few animation tools, each for one job:

  • animateFloatAsState, animateDpAsState, animateColorAsState…: one value moves smoothly to a new target. “When selected changes, fade the color.”
  • AnimatedVisibility: something appears or disappears with an enter and exit animation (fade, slide, expand).
  • AnimatedContent: one piece of content is replaced by another, like a number changing or a loading state turning into results.
  • Modifier.animateContentSize(): a container smoothly changes size when its content grows or shrinks.
  • updateTransition: several values change together because of one state, like a card’s size, color and corner radius when it’s selected.

Animations in Compose are interruptible: if the target changes halfway, the animation continues from where it is to the new target, without jumping.

Choose by shape: animate*AsState for a single target-driven value; AnimatedVisibility (enter/exit specs, MutableTransitionState to animate on first appearance) for presence; AnimatedContent(targetState, contentKey) with transitionSpec and SizeTransform for content swaps; updateTransition to coordinate several values from one state (inspectable in Android Studio’s Animation Preview); rememberInfiniteTransition for loops; Animatable for imperative, coroutine-driven animation (gestures with animateDecay, sequences, snapTo on drag). Specs: spring (default, velocity-preserving on interruption), tween, keyframes. Performance: an animated value read in composition (Modifier.offset(x = anim.value.dp), alpha(anim.value)) recomposes every frame; read it in layout (Modifier.offset { IntOffset(...) }) or draw (Modifier.graphicsLayer { alpha = anim.value }, drawBehind) via lambda modifiers so only those phases rerun. Shared element transitions (SharedTransitionLayout with Modifier.sharedElement/sharedBounds, integrated with Navigation Compose) handle list-to-detail continuity. Respect the system’s animator duration scale and reduced-motion preferences.

@Composable
fun PriceBadge(price: Int) {
    var lastPrice by remember { mutableIntStateOf(price) }
    val scale = remember { Animatable(1f) }
    LaunchedEffect(price) {                                  // bounce when the price changes
        if (price != lastPrice) {
            scale.animateTo(1.2f, spring(stiffness = Spring.StiffnessHigh))
            scale.animateTo(1f, spring(dampingRatio = Spring.DampingRatioMediumBouncy))
            lastPrice = price
        }
    }
    AnimatedContent(
        targetState = price,
        transitionSpec = { (slideInVertically { it } + fadeIn()) togetherWith (slideOutVertically { -it } + fadeOut()) },
        label = "price",
        modifier = Modifier.graphicsLayer { scaleX = scale.value; scaleY = scale.value },   // read in the draw phase
    ) { value ->
        Text("€$value", style = MaterialTheme.typography.titleMedium)
    }
}

@Composable
fun DetailsPanel(expanded: Boolean, onToggle: () -> Unit, details: String) {
    Column(Modifier.animateContentSize()) {                  // the column's height animates
        TextButton(onClick = onToggle) { Text(if (expanded) "Hide details" else "Show details") }
        AnimatedVisibility(visible = expanded, enter = fadeIn() + expandVertically(), exit = fadeOut() + shrinkVertically()) {
            Text(details)
        }
    }
}

@Composable
fun SwipeHint(active: Boolean) {
    val offsetX by animateDpAsState(if (active) 24.dp else 0.dp, label = "hint")
    Icon(
        Icons.AutoMirrored.Filled.ArrowForward, contentDescription = null,
        modifier = Modifier.offset { IntOffset(offsetX.roundToPx(), 0) },   // layout phase: no recomposition per frame
    )
}
  • AnimatedContent slides the old price up and out and the new one in from below whenever price changes.
  • Animatable + LaunchedEffect(price) runs a two-step bounce each time the price changes.
  • graphicsLayer { scaleX = … } applies the bounce while drawing, so the price text isn’t recomposed 60 times a second.
  • AnimatedVisibility fades and expands the details in and out; animateContentSize makes the panel grow smoothly instead of jumping.
  • offset { IntOffset(…) } (the lambda version) moves the icon during layout instead of recomposing it on every frame.

Predict the output

A button toggles a card's selected state. val elevation by animateDpAsState(if (selected) 8.dp else 0.dp) runs a 300 ms animation. The user taps twice quickly; the second tap comes 100 ms after the first. What does the elevation do?

Production puzzles

Spot the bugA pulsing dot that recomposes the screen

Tap the line with the bug.

@Composable
fun LiveIndicator(modifier: Modifier = Modifier) {
    val transition = rememberInfiniteTransition(label = "live")
    val alpha by transition.animateFloat(
        initialValue = 1f, targetValue = 0.2f,
        animationSpec = infiniteRepeatable(tween(800), RepeatMode.Reverse), label = "alpha",
    )
    Box(modifier.size(10.dp).alpha(alpha).background(Color.Red, CircleShape))
}

Predict the output

AnimatedContent(targetState = uiState) { state -> when (state) { is Loading -> Spinner(); is Loaded -> ProductList(state.items) } }. Every time a product's 'favorite' flag changes, uiState becomes a new Loaded(items) instance. What does the user see?

Exercisehard

Animate a list-to-detail transition

A product grid opens a detail screen with Navigation Compose. Design: the product image grows from its grid cell into the detail header, the title follows, and back navigation reverses it, including predictive back. What do you use, and what can go wrong?

›

Shared element transitions need a common scope that both screens are inside.

SolutionTry it yourself first
  • Wrap the NavHost in SharedTransitionLayout, and pass its SharedTransitionScope plus each destination’s AnimatedVisibilityScope (from composable { }) down to the grid cell and the detail header.
  • Apply Modifier.sharedElement(rememberSharedContentState("image-$id"), animatedVisibilityScope) to the image in both places, and sharedBounds to the title container (different content, shared bounds).
  • Predictive back works through Navigation Compose’s integration: the transition is driven by the back gesture progress.
  • Pitfalls: keys must match exactly and be unique per item; images should use the same cached source (Coil with the same memory cache key) so the detail doesn’t flash a placeholder; avoid heavy recomposition in the destination’s first frame; and test with slow animations (developer options) and with animations off, where the screens should simply switch.
Exerciseeasy

Animate a favorite button

A heart icon toggles a favorite. When it becomes a favorite, the icon should turn red and briefly grow; when un-favorited, turn gray. Write it with as little code as possible.

›

One state drives both the color and the size; two animate…AsState calls are enough.

SolutionTry it yourself first
@Composable
fun FavoriteButton(isFavorite: Boolean, onToggle: () -> Unit) {
    val tint by animateColorAsState(if (isFavorite) Color.Red else Color.Gray, label = "tint")
    val scale by animateFloatAsState(
        targetValue = if (isFavorite) 1.2f else 1f,
        animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
        label = "scale",
    )
    IconButton(onClick = onToggle) {
        Icon(
            imageVector = if (isFavorite) Icons.Filled.Favorite else Icons.Outlined.FavoriteBorder,
            contentDescription = if (isFavorite) "Remove from favorites" else "Add to favorites",
            tint = tint,
            modifier = Modifier.graphicsLayer { scaleX = scale; scaleY = scale },
        )
    }
}

Both values animate toward their new targets whenever isFavorite changes, and the bouncy spring gives the “pop”. The scale is applied in graphicsLayer, so it doesn’t recompose the icon every frame.

  • animate*AsState (one value), AnimatedVisibility (presence), AnimatedContent + contentKey + SizeTransform (swaps), updateTransition (coordinated values), rememberInfiniteTransition, Animatable (gestures, sequences).
  • Interruptible: springs keep velocity on retarget.
  • Read animated values in layout/draw (offset { }, graphicsLayer { }, drawBehind), not composition, or you recompose every frame.
  • Shared elements: SharedTransitionLayout, sharedElement/sharedBounds, Navigation Compose and predictive back.
  • Respect animator duration scale and reduced motion.

Check this part

  1. Which API animates something appearing and disappearing?

  2. The target of a running animation changes halfway. What happens?

  3. Why use graphicsLayer { alpha = a } instead of Modifier.alpha(a) for an animated value?

  4. AnimatedContent re-animates the whole list on every data change. Fix?

Pick the API by what changes: animate*AsState for one value, AnimatedVisibility for appearing and disappearing, AnimatedContent for swapping content, updateTransition for several values driven by one state, Animatable for gestures and sequences. Animations are interruptible and continue from the current value. Read animated values in the layout or draw phase (offset { }, graphicsLayer { }) so they don't recompose every frame.

Key takeaways

  • Compose measures each child once: use intrinsics, not double measuring.
  • Write custom arrangements with Layout, and check FlowRow before writing your own.
  • Pick the animation API by what changes: a value, visibility, content or size.
  • Animations are interruptible; apply animated values in graphicsLayer or lambda offset.
  • Know the layout costs: intrinsics, subcomposition, and why they matter in lists.
  • Reusable modifiers are Modifier.Nodes.
  • Defer state reads to the phase that needs them; check recomposition counts in Layout Inspector.
  • Key content transitions deliberately and test shared elements with predictive back.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.