skip to content

Jetpack Compose

Composable functions, state-driven recomposition, modifier chains and Material theming in place of XML layouts. Interviewers ask because Compose is now the default for new Android UI.

on this pageshow

explore

questions

page 1 of 2

In Compose, how do animateDpAsState and animateColorAsState animate a bouquet price badge, and what happens when the target changes mid-animation?

level: juniorimportance: must knowfreq 78%

answer

  1. pass a target, read a State
  2. remembered Animatable at the call site
  3. first target is the starting value
  4. retarget keeps current value and velocity
  5. default spec is spring(), not a tween

basics

~20 s

animateDpAsState and animateColorAsState take a target value and return a State that moves toward it each frame under a spring by default. A new target mid-flight redirects the running animation from its current value and velocity.

solid answer

~40 s

`animateDpAsState(targetValue)` and `animateColorAsState(targetValue)` are fire-and-forget: you compute the target from state (say, the selected bouquet size) and read the returned `State` with `by`. An `Animatable` is created and remembered at the call site with the first target as its starting value, so nothing animates on first composition. Each later target starts an animation; if one is already running it adjusts course from its current value **and velocity**. With no `animationSpec` they use `spring()` (`Spring.DampingRatioNoBouncy`, `Spring.StiffnessMedium`), which keeps velocity continuous on interruption; pass `tween(...)` or `keyframes { }` for timed motion. You cannot stop or cancel them except by removing the call from composition. Need that control? Use `Animatable` directly.

code

kotlin · 16 lines
kotlin
@Composable
fun PriceBadge(size: BouquetSize, price: String) {
    val large = size == BouquetSize.Large
    val badgeWidth by animateDpAsState(
        targetValue = if (large) 96.dp else 64.dp,
        label = "badgeWidth",
    )
    val badgeColor by animateColorAsState(
        targetValue = if (large) Color.Magenta else Color.LightGray,
        animationSpec = tween(durationMillis = 250),
        label = "badgeColor",
    )
    Box(Modifier.width(badgeWidth).background(badgeColor)) {
        Text(price)
    }
}

go deeper

for a junior

Recall the shape: pass a target, get a State back, read it with by. Name the default spring and show how to pass a tween instead.

for a middle

Explain the remembered Animatable behind each call, why the first composition does not animate, and how a new target redirects from the current value and velocity.

for a senior

Show where animate*AsState stops being enough: no stop or cancel, finishedListener skipped for interrupted runs, and values that must stay in lockstep. Move those cases to Animatable or updateTransition.

for a principal

Weigh the simplest API against control. A team rule might default to animate*AsState with spring specs for state-driven UI, and allow Animatable only where gestures or cancellation need it.

## What the animate*AsState family is The **animate*AsState** functions are the simplest animation APIs in Compose. Each one animates a **single value** of one type: `animateFloatAsState`, `animateDpAsState`, `animateColorAsState`, `animateIntAsState`, `animateOffsetAsState`, `animateSizeAsState`, `animateRectAsState`, `animateIntOffsetAsState` and `animateIntSizeAsState`. For any other type, `animateValueAsState` takes a `TwoWayConverter` that maps your type to an `AnimationVector` and back. You give the function a **target value**, usually an expression over state such as `if (size == BouquetSize.Large) 96.dp else 64.dp`. It returns a `State<T>`. Reading that state with `by` gives you the animated value. While an animation runs, the value changes every frame, and whatever reads it (a composable, or a layout or draw lambda) is updated. ## What happens under the hood The Android documentation describes the mechanism plainly: an **`Animatable`** is created and remembered at the call site, with the **first target value as its initial value**. Three behaviours follow from that: - **No animation on first composition.** The badge appears at its first target. To animate in on first display, use `Animatable` with an initial value different from the first target, or a transition started from a `MutableTransitionState`. - **Every new target starts an animation.** When recomposition passes a different target, an animation toward it starts automatically. - **Interruption is handled for you.** If an animation is already in flight, it is redirected: the new animation starts from the **current value and velocity**, not from the old start or the old target. ## The default spec, and when to change it With no `animationSpec`, these functions use a **spring**. For `animateFloatAsState` the default is a `spring()` with a 0.01 visibility threshold; for `animateDpAsState` it is `spring(visibilityThreshold = Dp.VisibilityThreshold)`. The **visibility threshold** is the distance from the target at which the animation counts as finished, so a spring does not keep settling invisibly for many frames. The spring defaults are `dampingRatio = Spring.DampingRatioNoBouncy` (1f) and `stiffness = Spring.StiffnessMedium` (1500f). | Spec | How you write it | What it gives you | |---|---|---| | `spring` | `spring(dampingRatio, stiffness)` | physics motion, no fixed duration, velocity carried across interruptions | | `tween` | `tween(durationMillis = 300, delayMillis = 0, easing = FastOutSlowInEasing)` (the defaults) | a fixed duration along an easing curve | | `keyframes` | `keyframes { durationMillis = 375; 0.4f at 75 }` | values pinned at timestamps | | `snap` | `snap(delayMillis = 50)` | jumps to the target, optionally after a delay | The documentation says a spring handles interruptions more smoothly than a duration-based spec because it **guarantees continuity of velocity** when the target changes mid-animation. A `tween` restarts its full duration from wherever the value is, so a badge that is tapped repeatedly can look jerky. Choose a `tween` when the motion must take a fixed time, such as a colour fade timed to match another element. ## Applying it to the price badge For a bouquet-size selector, two values change together when the size changes: 1. The badge width: `animateDpAsState(targetValue = if (large) 96.dp else 64.dp, label = "badgeWidth")`. 2. The badge colour: `animateColorAsState(targetValue = ..., animationSpec = tween(250), label = "badgeColor")`. Each call animates on its own. If the two must stay in lockstep or share one notion of "done", a single `updateTransition` with child animations is the better fit. ## Limits worth knowing - **No stop or cancel.** The KDoc says it directly: these functions cannot be cancelled or stopped without removing the composable from the tree. For a stoppable or gesture-driven value, use `Animatable` with `stop()`, `snapTo()` and `animateTo()`. - **`finishedListener`** is called with the final value when an animation reaches its target. If a newer target interrupts an animation, the listener does not run for the interrupted one. It runs once the newer animation reaches its target. - **`label`** names the animation in Android Studio's animation tooling. Give each call a distinct label. - **Reading cost.** The animated state changes every frame. Reading it in a layout or draw lambda instead of in composition is a modifier technique covered with Compose modifiers, not here. - **Leaving composition ends it.** The animation belongs to the call site, so removing that composable stops the animation along with it. Once these points are clear, the API rarely surprises you: compute the target, read the state, let the spring absorb rapid changes, and switch to `Animatable` when you need imperative control.

  • Why does the badge not animate the first time the screen appears, and how would you make it animate in?
    The remembered `Animatable` starts at the first target value, so the first composition just shows that value. To animate on first display, remember an `Animatable` with a different initial value and call `animateTo` in a `LaunchedEffect`, or drive the value from a transition started with a `MutableTransitionState` whose initial state differs from its target.
  • A product owner wants a tap to freeze the badge mid-animation; can animateDpAsState do that?
    No. Its KDoc says it cannot be cancelled or stopped without removing the composable from the tree. Hold the value in a remembered `Animatable` instead: `stop()` halts it in place without jumping to the target, and `animateTo` resumes later from wherever it stopped.
  • How do you animate a type with no built-in animate*AsState, such as a data class holding two Dp values?
    Use `animateValueAsState` with a `TwoWayConverter` that turns the value into an `AnimationVector2D` and back. Each dimension of the vector animates with its own velocity tracking, so both fields move smoothly and handle interruption the same way the built-in types do.

  • animate*AsState animates from zero on the first composition.
  • A new target waits for the running animation to finish first.
  • The default animationSpec is a 300 ms tween.
  • You can call stop() on the State that animateDpAsState returns.
  • finishedListener fires for every interrupted animation as well.
open as a page

In Compose, how does AnimatedVisibility slide an order summary in and out, and why does a plain if-statement not animate its removal?

level: juniorimportance: must knowfreq 74%

basics

~20 s

AnimatedVisibility runs an EnterTransition when visible becomes true and an ExitTransition when it becomes false, keeping the content composed until the exit finishes. An if-statement removes the content at once, so there is nothing left to animate.

open as a page

In Jetpack Compose, what does the @Composable annotation change about a function, and where may a composable be called from?

level: juniorimportance: must knowfreq 80%

basics

~20 s

@Composable changes a function's type: the Compose compiler passes an implicit composition context into it, so it can only be called from another composable function or composable lambda, never from onClick, a coroutine or an ordinary function.

open as a page

In Jetpack Compose Material 3, how does MaterialTheme supply colors, typography and shapes to components, and how should a composable read them?

level: juniorimportance: must knowfreq 72%

basics

~20 s

MaterialTheme takes a ColorScheme, a Typography and a Shapes and provides them to everything in its content. Material components use them as defaults, and your own composables read MaterialTheme.colorScheme, .typography and .shapes instead of hardcoding values.

open as a page

In Jetpack Compose, why does Modifier.padding(16.dp).background(Color.Red) render differently from Modifier.background(Color.Red).padding(16.dp)?

level: juniorimportance: must knowfreq 72%

basics

~10 s

Each modifier wraps everything after it. Padding then background insets first, so red fills only the inner area; background then padding paints the whole padded area red, then insets the content.

open as a page

In Navigation 3, who owns the back stack, and how do NavDisplay, entryProvider and onBack turn that list into screens?

level: juniorimportance: must knowfreq 55%

basics

~20 s

In Navigation 3 the app owns the back stack, an observable list of keys it edits. NavDisplay observes the list, asks entryProvider for each key's NavEntry, shows the top one and calls onBack when the user goes back.

open as a page

In Jetpack Compose, when should a screen use LazyColumn instead of a Column, and what does LazyColumn do differently?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Use LazyColumn when the list is long or of unknown length. A Column composes and lays out every child; LazyColumn composes only the items near the viewport and describes them through a LazyListScope DSL of item and items calls.

open as a page

In Jetpack Compose, why do you use rememberCoroutineScope rather than LaunchedEffect to show a snackbar from a button's onClick?

level: juniorimportance: must knowfreq 70%

basics

~20 s

LaunchedEffect is a composable, so it cannot be called from onClick, and showSnackbar is a suspend function that needs a coroutine. rememberCoroutineScope returns a scope bound to that point of the composition: launch from the click, cancelled when the composable leaves.

open as a page

In Jetpack Compose, why does a quantity counter kept in a plain local `var` never update, and what do `remember` and `mutableStateOf` each fix?

level: juniorimportance: must knowfreq 85%

basics

~20 s

A plain local is neither observed nor kept: changing it schedules nothing, and every recomposition re-runs the function and resets it. mutableStateOf makes writes recompose whatever read the value; remember keeps that state object in the Composition between recompositions.

open as a page

In a Jetpack Compose UI test using the v2 createComposeRule, how do you find a node by text or test tag, click it and assert?

level: juniorimportance: must knowfreq 72%

basics

~10 s

Create the rule with the v2 createComposeRule, call setContent once, find a node with onNodeWithText or onNodeWithTag (the tag comes from Modifier.testTag), act with performClick, and check it with assertIsDisplayed, assertExists or assertTextEquals.

open as a page

In a View-based Android app, how do you place Jetpack Compose UI inside an existing XML screen using ComposeView?

level: juniorimportance: must knowfreq 65%

basics

~20 s

Add androidx.compose.ui.platform.ComposeView to the XML layout or create it in code, then call setContent with your composables wrapped in a theme. It is an ordinary View, so the rest of the screen stays as it is.

open as a page

In Jetpack Compose, what makes a composable restartable or skippable, and how does recomposition use those two properties when state changes?

level: middleimportance: must knowfreq 66%

basics

~20 s

Restartable means a composable is a scope where recomposition can start re-executing; skippable means Compose may pass over a call whose parameters equal last time's. A state change re-runs the nearest restartable scope that read it and skips unchanged skippable calls inside.

open as a page

In Jetpack Compose Material 3, how do you choose between dynamic color and a brand ColorScheme in light and dark, and what changes below Android 12?

level: middleimportance: must knowfreq 64%

basics

~20 s

The app's theme function picks the scheme: on Android 12 (API 31) and up, dynamicDarkColorScheme or dynamicLightColorScheme from the wallpaper if wanted; otherwise brand darkColorScheme or lightColorScheme, chosen with isSystemInDarkTheme(). Below Android 12 only the brand schemes exist.

open as a page

In Jetpack Compose, how do Row's weight, Arrangement and Alignment share out space, and how does Box let a badge overlap an avatar?

level: middleimportance: must knowfreq 60%

basics

~20 s

Row measures unweighted children first, then splits the leftover width by weight; Arrangement spaces children along the main axis and Alignment places them across it. Box stacks children, and BoxScope.align with offset puts a badge over the avatar's corner.

open as a page

In Jetpack Compose lazy lists and grids, what do the key and contentType parameters of items() do, and what breaks without a key?

level: middleimportance: must knowfreq 70%

basics

~20 s

Without a key, a lazy item's state and the scroll anchor follow its position, so an insert or a re-sort attaches state to the wrong product. A unique, Bundle-saveable key ties them to the item; contentType limits reuse to like items.

open as a page

In Jetpack Compose, how do you register a sensor listener with DisposableEffect so that it is removed reliably, and when does onDispose run?

level: middleimportance: must knowfreq 65%

basics

~10 s

Register the listener inside DisposableEffect(sensorManager) and unregister it in onDispose, the block's last statement. onDispose runs once per effect run: before the effect re-runs for a changed key, and when the effect leaves composition.

open as a page

In Jetpack Compose, what do the keys passed to LaunchedEffect decide, and what goes wrong when you choose the wrong ones?

level: middleimportance: must knowfreq 75%

basics

~20 s

LaunchedEffect's keys are its identity: its coroutine starts when it enters composition, is cancelled and relaunched when any key changes by equals(), and is cancelled when it leaves. Too few keys leave stale work running; unstable keys restart it constantly.

open as a page

In Jetpack Compose, why does a checkout promo code survive rotation with `rememberSaveable` but not with `remember`, and how do you save a custom type?

level: middleimportance: must knowfreq 72%

basics

~20 s

remember lives in the Composition, which is rebuilt when the activity is recreated, so its value is lost. rememberSaveable also writes the value into saved instance state, restoring it after rotation and system-initiated process death; other types need @Parcelize or a Saver.

open as a page

In Jetpack Compose, how do you hoist a checkout promo-code field's state so the field composable becomes stateless, and what does the caller gain?

level: middleimportance: must knowfreq 75%

basics

~20 s

Move the remembered value out of the field and replace it with two parameters: the current value and an onValueChange-style callback. The caller then owns the single source of truth, can share it with the price summary, and can intercept or reject each edit.

open as a page

In a Compose UI test, why does onNodeWithTag miss a test tag on a Text inside a clickable row, and what does useUnmergedTree change?

level: middleimportance: must knowfreq 52%

basics

~20 s

A clickable row merges its descendants, so in the default merged tree the child Text vanishes into the row; its text merges up, its test tag never does. useUnmergedTree = true searches the tree where the child is still its own node.

open as a page

In Jetpack Compose, which ViewCompositionStrategy should a ComposeView inside a Fragment use, and what goes wrong with the default strategy?

level: middleimportance: must knowfreq 60%

basics

~10 s

Use ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed. The default disposes the composition whenever the ComposeView detaches from the window, so remembered state can be lost while the Fragment's view still exists.

open as a page

In a multi-module app on Jetpack Compose, a product row re-runs every time its screen recomposes although its data did not change; how do you find and fix the cause?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Compose compiler reports usually show the row's parameter unstable (a List, or a model from a non-Compose module) and it is re-allocated each pass. Stop re-allocating, or make the type stable: @Immutable, a stability configuration file or a UI wrapper.

open as a page

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%

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.

open as a page

In Compose, how does updateTransition drive several values from one bouquet-card state, and how does rememberInfiniteTransition differ for a pulsing preparing indicator?

level: middleimportance: should knowfreq 48%

basics

~20 s

updateTransition holds one target state and runs child animations such as animateDp and animateColor toward per-state values together, each with its own finite spec. rememberInfiniteTransition has no target state: its children loop with infiniteRepeatable for as long as they are composed.

open as a page

In Jetpack Compose, what is a slot API, and why do components such as Scaffold and Button take @Composable lambdas instead of plain values?

level: middleimportance: should knowfreq 42%

basics

~20 s

A slot API exposes parameters typed as composable lambdas, such as Scaffold's topBar and content or Button's content, so callers fill a space with any UI instead of the component exposing a parameter for every option of its children.

open as a page

What does Jetpack Compose's strong skipping mode, on by default since Kotlin 2.0.20, change about skipping composables and about lambdas?

level: middleimportance: should knowfreq 54%

basics

~20 s

Strong skipping makes every restartable composable skippable, comparing stable parameters with equals() and unstable ones by instance (===). It also remembers each lambda inside a composable, keyed on its captures, so recomposition stops handing children new lambda instances.

open as a page

In Jetpack Compose Material 3, how does Text inside a Surface get a readable color without a color argument, and when does that fail?

level: middleimportance: should knowfreq 46%

basics

~20 s

Surface sets LocalContentColor to contentColorFor(its color), which maps a scheme background such as primary to its on-role, onPrimary. Text and Icon default to LocalContentColor. It fails when the background is not a scheme color, or is painted with Modifier.background.

open as a page

In Navigation 3, how do rememberNavBackStack, NavKey and @Serializable keep a back stack through rotation and process death, and what breaks?

level: middleimportance: should knowfreq 45%

basics

~20 s

rememberNavBackStack saves the list of keys with the Activity's saved state, so it survives rotation and process death. Every key must implement NavKey and be @Serializable; a key missing the annotation still compiles but fails when the stack is saved.

open as a page

In Navigation Compose, how do type-safe routes work with @Serializable route classes, composable<T>() and toRoute(), and what do they replace?

level: middleimportance: should knowfreq 58%

basics

~10 s

Since Navigation 2.8.0, each destination is a @Serializable object or data class. You register it with composable<T>(), navigate with navController.navigate(ProductDetail(id)), and rebuild the arguments with backStackEntry.toRoute<T>(), replacing string routes and navArgument lists.

open as a page

In Jetpack Compose on Android, how does `collectAsStateWithLifecycle` differ from `collectAsState` when a checkout screen collects a live price-summary Flow?

level: middleimportance: should knowfreq 62%

basics

~20 s

collectAsState collects for as long as the composable is in the composition, even while the app sits in the background. collectAsStateWithLifecycle stops collecting when the lifecycle drops below minActiveState, STARTED by default, and resumes above it, so Android screens should prefer it.

open as a page

showing 1–30 of 58