0Pricing
Android Academy · Lesson

animate*AsState Basics

Smoothly animate single values.

Animate a Single Value

The simplest way to animate in Compose is the animate*AsState family. You give it a target value, and it returns a State that smoothly animates from the current value to the target whenever the target changes.

There's a variant for each common type: animateFloatAsState, animateDpAsState, animateColorAsState, animateOffsetAsState, and more.

animateFloatAsState

animateFloatAsState animates a single Float. A common use is opacity (alpha). When visible flips, the returned alpha glides between 0f and 1f.

Note the by keyword: it lets you read the animated State<Float> directly as a plain Float.

@Composable
fun FadingLabel(visible: Boolean) {
    val alpha by animateFloatAsState(
        targetValue = if (visible) 1f else 0f,
        label = "alpha"
    )
    Text(
        "Hello",
        modifier = Modifier.graphicsLayer { this.alpha = alpha }
    )
}

All lessons in this course

  1. Why Animations Matter
  2. animate*AsState Basics
  3. AnimatedVisibility and Transitions
  4. Gesture and Spring Animations
← Back to Android Academy