DEV Community

Cover image for Spice up your Compose button
Muhamad Wahyudin
Muhamad Wahyudin

Posted on Edited on AI-assisted

Spice up your Compose button

I wanted a reason to go through the animation APIs Compose ships: animateFloatAsState, Animatable, graphicsLayer, AnimatedContent, plus the semantics modifiers that make any of it audible. A button is a good vehicle because the one Material gives you is already finished. Press it and something happens without a line of motion code from you. So the experiment has two halves: what the stock button does on its own, then what those APIs add when the button has to say something while it works, and whether that turns a control into a micro-interaction worth noticing.

The floor: what Button already does

The button everybody writes:

Button(onClick = {}) { Text("Press me") }
Enter fullscreen mode Exit fullscreen mode

Press it and you get a ripple clipped to the shape, plus the pressed state layer over the container. Colors come from ButtonDefaults.buttonColors(), the label from labelLarge, and the hit area from ButtonDefaults.MinHeight raised to 48dp by minimumInteractiveComponentSize. Role, click handling and press interactions are wired.

What doesn't happen is geometry. FilledButtonTokens.ContainerElevation is Level0 at rest, pressed and focused, so a filled button has no shadow to animate, and the shape is a constructor parameter that holds still for the whole interaction.

material3 1.5 does ship a pressed-shape morph, and it's opt-in:

@OptIn(ExperimentalMaterial3ExpressiveApi::class)
Button(onClick = {}, shapes = ButtonDefaults.shapes()) { Text("Press me") }
Enter fullscreen mode Exit fullscreen mode

With the defaults that's CornerFull to CornerSmall while the finger is down, through rememberAnimatedShape. One axis, one spec, and the source is deliberate about the character it wants: MotionSchemeKeyTokens.DefaultEffects is intentional here to prevent any bounce in this component.

That's a good default for a component used on every screen. It also marks the edge of what the component knows: how far a press travels, what a release does with the velocity it had, and what any of it means to TalkBack.

What the APIs add

What I wanted Stock button What I reached for
press geometry: scale and lift ripple and state layer only MutableInteractionSource + animateFloatAsState + graphicsLayer
a release that keeps its momentum ripple dismissal Animatable + animateTo(initialVelocity = …)
four states moving as one property static shape and colors, opt-in single-axis morph Animatable<Float> + lerpMorph + AnimatedContent
a state TalkBack can announce role and label semantics { stateDescription; liveRegion }
ripple muted, or reshaped while morphing ripple clipped to a fixed shape indication parameter + a hand-built clickable

The five rows above map to four sections, in order: press geometry, release, the morph, then semantics and indication together, because TalkBack and the ripple live on the same node. Each section is the API plus the wiring that makes it work, since the wiring is where most of these go wrong.

1. Press geometry from the interaction stream

Press feedback usually starts with pointer input. It doesn't need any. MutableInteractionSource already publishes press and release, and collectIsPressedAsState() turns that into a boolean:

/** Press progress from the interaction stream: 0f at rest, 1f fully pressed, spring-smoothed. */
@Composable
fun rememberPressProgress(
    source: MutableInteractionSource,
    spec: AnimationSpec<Float> = spring(dampingRatio = 0.4f, stiffness = 900f),
): State<Float> {
    val pressed by source.collectIsPressedAsState()
    return animateFloatAsState(if (pressed) 1f else 0f, spec, label = "pressProgress")
}
Enter fullscreen mode Exit fullscreen mode

The wiring matters as much as the API. Surface(onClick = …) builds its own MutableInteractionSource unless you hand it one, and a press travelling on a different source never reaches your collector. So the container owns the source and passes it in:

@Composable
fun PressableSurface(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    pressModifier: (State<Float>) -> Modifier = { Modifier },
    content: @Composable () -> Unit,
) {
    val interactionSource = remember { MutableInteractionSource() }
    val pressProgress = rememberPressProgress(interactionSource)

    Surface(
        onClick = onClick,
        modifier = modifier.then(pressModifier(pressProgress)),
        interactionSource = interactionSource,
    ) { content() }
}
Enter fullscreen mode Exit fullscreen mode

Call sites stay dumb: pressModifier = { Modifier.bouncePress(it, liftPx) }. Any button that wants the bounce gets it without knowing where the press came from.

Two pure functions turn that progress into pixels, and the button never learns anything else:

fun bounceScale(progress: Float): Float = lerp(1f, BounceMotion.PressedScale, progress.coerceIn(0f, 1f))

/** Vertical travel in px for a press progress; `liftPx` is the fully-pressed depth. */
fun bounceLift(progress: Float, liftPx: Float): Float = liftPx * progress.coerceIn(0f, 1f)

fun Modifier.bouncePress(pressProgress: State<Float>, liftPx: Float): Modifier = graphicsLayer {
    val scale = bounceScale(pressProgress.value)
    scaleX = scale
    scaleY = scale
    translationY = bounceLift(pressProgress.value, liftPx)
}
Enter fullscreen mode Exit fullscreen mode

Two details there carry the chapter. lerp comes from androidx.compose.ui.util, and the mapping is pure, which is why the test asserts bounceScale(0.5f) == 0.975f on a JVM without a device. Then pressProgress.value is read inside graphicsLayer, so each frame of the press is a draw-phase change: no recomposition, no text relayout, no per-frame allocation.

That inner read is the whole reason the modifier is graphicsLayer { } and not Modifier.scale(...). The shorthand takes a plain float, which means the state has to be read during composition, and the button recomposes on every animation frame just to pass a slightly different number down. The lambda form defers the read to the draw phase, where a new value only costs a redraw.

One press, frame by frame

One press. 0.95 scale and a 2dp drop, no pointer handling: the interaction stream already had it.

PressedScale = 0.95f with a 2dp drop isn't much motion, and that's deliberate. A button that scales to 0.9 reads as a toy inside a list. Feel is a knob: the file also names a tighter press-in spring (0.35, 2200) and a softer release (0.45, 1200). Neither is wired up. The shared spring(0.4f, 900f) above was enough for the demo, so those two sit there as the first thing to try when the press feels sluggish on a cheap device. Cheaper to say that than to pretend every constant is load-bearing.

2. Release with the velocity it had

animateFloatAsState owns one value and one spec. That's fine until the finger leaves before the animation lands. A spring's release depends on how fast it was moving at that instant, and the black box won't hand you that velocity.

Animatable will. It keeps the value and hands you a handle on it, so the demo does a little setup first:

val hold = remember { Animatable(0f) }
val scope = rememberCoroutineScope()
Enter fullscreen mode Exit fullscreen mode

Then the gesture drives the value instead of reading it:

detectTapGestures(
    onPress = {
        val pressJob = scope.launch { hold.animateTo(1f, InterruptionMotion.PressIn) }
        tryAwaitRelease()
        pressJob.cancel()
        val carried = hold.velocity
        hold.animateTo(0f, InterruptionMotion.Settle, initialVelocity = carried)
    },
)
Enter fullscreen mode Exit fullscreen mode

The order matters. pressJob.cancel() runs before hold.velocity is read, otherwise you sample a value that's still being animated and carry the wrong number. tryAwaitRelease() returns the moment the pointer lifts, mid-spring. initialVelocity is what lets the pill continue from where it was instead of decelerating from full press, and that's the whole difference between a button that responds and a button that snaps back on its own schedule.

The carried velocity is in progress units per second, the same units the spec works in, so nothing needs converting. What it does need is room: Settle uses stiffness 1100 against the press-in's 1800. A stiffer release eats the carried velocity before you can see it, and then the demo teaches nothing. Softer, and a hard flick overshoots once, which is the read you want from a pressed pill.

The second demo in the same file reverses direction 90ms in: animateTo(1f), then animateTo(0f) a moment later. The value continues from its last frame rather than restarting at zero, so it reads as interrupted rather than retriggered. You get that from Animatable itself, no extra wiring.

Readout after a 70ms tap

A 70ms tap: the value is back at rest, the velocity it carried into the spring is not.

3. One progress axis per morph

A button that goes idle → loading → success → failed has at least three things moving: container color, corner radius, and width (the label turns into a spinner). Container and corner could ride two animate*AsState calls, and then you own two specs and two retargets that drift the first time a state change lands mid-morph. What I wanted instead was one number every consumer reads: at t = 0.4, corner, container and content color are all at 0.4.

/** Everything that changes between states, in one value. */
data class MorphVisuals(
    val container: Color,
    val content: Color,
    val corner: Dp,
)

/** Pure: the whole morph between two visual states. `t = 0` is [from], `t = 1` is [to]. */
fun lerpMorph(from: MorphVisuals, to: MorphVisuals, t: Float): MorphVisuals
Enter fullscreen mode Exit fullscreen mode

Every property derives from the same t, and MorphMotion.ProgressSpec is the only duration behind the shape and the colors: a 320ms tween with FastOutSlowInEasing.

The four states are app state

None of the four states is an animation. ActionState is plain app state, the kind a ViewModel would own, and a small holder moves it around:

sealed interface ActionState {
    data object Idle : ActionState
    data object Loading : ActionState
    data object Success : ActionState
    data object Failed : ActionState
}

class ActionRunner {
    var state by mutableStateOf<ActionState>(ActionState.Idle)
        private set

    private var run by mutableIntStateOf(0)

    /** Tap: start a run, or cut the result dwell short. */
    fun startOrReset() {
        if (state == ActionState.Idle) {
            run += 1
            state = ActionState.Loading
        } else {
            state = ActionState.Idle
        }
    }

    /** The fake request. Every third run fails, so the failure path is visible without faking it. */
    suspend fun simulate() {
        when (state) {
            ActionState.Idle -> Unit
            ActionState.Loading -> {
                delay(FakeWorkMillis)          // 1.8s
                state = if (run % 3 == 0) ActionState.Failed else ActionState.Success
            }
            ActionState.Success, ActionState.Failed -> {
                delay(ResultDwellMillis)       // 1.4s
                state = ActionState.Idle
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

rememberActionRunner() runs simulate() in a LaunchedEffect(runner.state), so the auto-reset is cancelled by any tap that lands during the result window. Nothing in that class mentions a color, a corner radius or a duration. If you swap the fake request for a real one, this file doesn't change. The demo hands that runner's startOrReset to the button as onClick, which is the whole wiring between a finger and a morph: tap moves the state machine, the state machine moves the target, the target moves t.

The button then maps each state to a look, and gets four of them:

ActionState.Idle    -> MorphVisuals(primary, onPrimary, 28.dp)
ActionState.Loading -> MorphVisuals(secondaryContainer, onSecondaryContainer, 18.dp)
ActionState.Success -> MorphVisuals(tertiary, onTertiary, 26.dp)
ActionState.Failed  -> MorphVisuals(errorContainer, onErrorContainer, 22.dp)
Enter fullscreen mode Exit fullscreen mode

Four looks, one transition at a time. rememberMorphVisuals holds from, to and a single progress, so a state change never adds another animation: it retargets the pair that's already there. Read progress as distance through the current transition; which state you're in lives in from and to. That's the shift if you come from animateFloatAsState(targetValue = if (loading) 1f else 0f), where the target is a boolean and you're stuck at two looks.

Concretely, tap on Idle and the corner goes 28dp to 18dp while the container goes primary to secondaryContainer and the label gives way to a spinner. The spinner measures differently from the label, so the width moves with the content rather than with t. When the fake request lands, Success takes over from Loading: corner 18dp to 26dp, container to tertiary, spinner to tick. Tapping during the result window reverses back to Idle from wherever the current frame sits.

The container is the first consumer: corner and colors go straight into RoundedCornerShape(visuals.corner) and color = visuals.container, with no intermediate state and no second animation to keep in sync.

Retargeting needs one extra line. Swap to while progress sits at 0.4 and the next frame jumps back to the old start unless the current frame is baked into it first:

LaunchedEffect(target) {
    if (to.value != target) {
        // Bake the frame we are on into `from`, so retargeting mid-morph never jumps.
        from.value = lerpMorph(from.value, to.value, progress.value)
        to.value = target
        progress.snapTo(0f)
        progress.animateTo(1f, MorphMotion.ProgressSpec)
    }
}
Enter fullscreen mode Exit fullscreen mode

from becomes the frame you're on before the new target is adopted, so interrupting a morph is continuous. progress is remembered at 1f, which is why the first composition shows the idle pill already settled instead of morphing in from nothing. The test asserts the invariant rather than the pixels: at t = 0 you get from, at t = 1 you get to, corner and colors agree at every sampled t, and anything outside 0..1 clamps instead of overshooting.

Width is the second consumer, and it can't ride t. It follows content, so it goes through AnimatedContent: the fade and scale of the incoming label run on ContentSpec, a 160ms tween, and SizeTransform carries the container's width to whatever the new content measures. You can't lerp toward a measurement you don't have yet, so the incoming state is laid out first and the box moves to meet it.

clip = false on that size transform is what lets the incoming label draw past the outgoing box while the width catches up. The pill already clips to the animated corner radius, so the extra clip would only cut the label mid-swap. One clip, owned by the thing that has the shape.

The two durations are deliberately unequal. The label lands in 160ms while the container is still 160ms into its 320ms shape change, which reads as content first and pill catching up. Match them and the morph looks like one rigid object resizing instead of a shape reacting to what's inside it.

One tap: Run action, spinner, Success/Failed, then back to Run action

One tap, the whole cycle. Label and spinner swap in 160ms while the container is still halfway through its 320ms shape change, and the width in between is SizeTransform's job.

4. State for TalkBack, indication for everyone else

This is the chapter that justified the other three. A button whose states are a spinner, a tick and a red icon says nothing to a screen reader, and stateDescription alone doesn't fix it because the node has no name to hang it on.

The fix is one table, read twice:

private fun announcement(state: ActionState, label: String): Announcement = when (state) {
    ActionState.Idle -> Announcement(content = null, state = "Ready")
    ActionState.Loading -> Announcement(content = "$label, working", state = "In progress")
    ActionState.Success -> Announcement(content = "$label, complete", state = "Succeeded")
    ActionState.Failed -> Announcement(content = "$label, failed", state = "Failed")
}

fun Modifier.polishedSemantics(state: ActionState, label: String): Modifier {
    val said = announcement(state, label)
    return semantics {
        liveRegion = LiveRegionMode.Polite
        stateDescription = said.state
        if (said.content != null) contentDescription = said.content
    }
}
Enter fullscreen mode Exit fullscreen mode

content is null at idle because the button still shows visible text. The other three states are icon-only, so they get a spoken name. liveRegion = LiveRegionMode.Polite is what makes the change audible without focus moving. The chapter also prints the spoken line on screen, from the same announcement() call, so the caption a sighted user reads and the words TalkBack says can't drift apart.

The readout needed a delay to be honest. A fake request finishes in 1.8s and the runner drops back to idle 1.4s after that, so a readout bound straight to state flashes the result and returns to "Ready" before anyone finishes the sentence. LaunchedEffect(runner.state) waits out ReadoutDwellMillis before showing idle again, which lets the result stay on screen while TalkBack is still speaking it. That's a demo affordance, and it's also the kind of thing a real screen would need if the state line were the only confirmation a user got.

Four states and what TalkBack says

Idle, loading, success, failed, each with the line it announces.

Ripple was the surprise. indication = null on a clickable really is no ripple, and Material's Surface(onClick) has no switch for that:

val ripple = ripple(bounded = ButtonMotion.RippleBounded, radius = ButtonMotion.RippleRadius)
val indication: Indication? = when (mode) {
    RippleMode.Default -> ripple
    RippleMode.MutedWhileBusy -> if (busy) null else ripple
    RippleMode.None -> null
}
Enter fullscreen mode Exit fullscreen mode

Surface remains the right container for an ordinary button: it brings the 48dp touch target, Role.Button, indication and LocalContentColor propagation for free. The moment you need indication muted, or the ripple clipped to a shape that's mid-morph, you build the pill by hand and the modifier order is the part that matters:

Box(
    modifier = Modifier
        .minimumInteractiveComponentSize()
        .clip(shape)
        .background(container)
        .clickable(
            interactionSource = interactionSource,
            indication = indication,
            role = Role.Button,
            onClick = onClick,
        ),
)
Enter fullscreen mode Exit fullscreen mode

Clip first so both the background and the ripple inherit the current shape, background second so the ripple lands on top of it, clickable last so the indication is clipped by the boundary it was given. A bounded ripple with an unspecified radius fills the node it's clipped to, which is exactly the behaviour you want against a corner radius that moves. minimumInteractiveComponentSize() is a no-op at this pill's 56dp height, and the line that keeps a smaller variant tappable.

![Muted while busy

Muted while busy, and the pill is already squarer than a capsule. This is the switch Surface(onClick) doesn't have.

Conclusion

The stock Button ships finished: ripple clipped to the shape, pressed state layer, colors from the theme, 48dp target, a role TalkBack can read. That's the right answer for a button that fires an action and stops there.

The animation APIs get you past that ceiling. The same button can react to how you press it, carry momentum into the release, hold four states in a single number, and say out loud which state it's in. None of it needs another component library, only the APIs and modifiers already listed above.

That's the interesting part. The default button is a control; a control that confirms the tap, shows the work and reports the result is a micro-interaction the user notices without being told to. Compose ships the pieces, and the only decision left is how far you want to take them.

Repo: github.com/hyuwah/composelab. Each chapter is one file under ui/playground/button/.

Top comments (0)