{% setvar book_path %}/reference/androidx/_book.yaml{% endsetvar %} {% include "_shared/_reference-head-tags.html" %}

AnimatableKt

public final class AnimatableKt


Summary

Public methods

static final @NonNull Animatable<@NonNull Float, @NonNull AnimationVector1D>
Animatable(float initialValue, float visibilityThreshold)

This Animatable function creates a float value holder that automatically animates its value when the value is changed via animateTo.

Public methods

Animatable

public static final @NonNull Animatable<@NonNull Float, @NonNull AnimationVector1DAnimatable(float initialValue, float visibilityThreshold)

This Animatable function creates a float value holder that automatically animates its value when the value is changed via animateTo. Animatable supports value change during an ongoing value change animation. When that happens, a new animation will transition Animatable from its current value (i.e. value at the point of interruption) to the new target. This ensures that the value change is always continuous using animateTo. If spring animation (i.e. default animation) is used with animateTo, the velocity change will be guaranteed to be continuous as well.

Unlike AnimationState, Animatable ensures mutual exclusiveness on its animation. To do so, when a new animation is started via animateTo (or animateDecay), any ongoing animation job will be cancelled.

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.graphicsLayer

fun Modifier.fadeIn(): Modifier = composed {
    // Creates an `Animatable` and remembers it.
    val alphaAnimation = remember { Animatable(0f) }
    // Launches a coroutine for the animation when entering the composition.
    // Uses `alphaAnimation` as the subject so the job in `LaunchedEffect` will run only when
    // `alphaAnimation` is created, which happens one time when the modifier enters
    // composition.
    LaunchedEffect(alphaAnimation) {
        // Animates to 1f from 0f for the fade-in, and uses a 500ms tween animation.
        alphaAnimation.animateTo(
            targetValue = 1f,
            // Default animationSpec uses [spring] animation, here we overwrite the default.
            animationSpec = tween(500)
        )
    }
    this.graphicsLayer(alpha = alphaAnimation.value)
}
Parameters
float initialValue

initial value of the animatable value holder

float visibilityThreshold

Threshold at which the animation may round off to its target value. Spring.DefaultDisplacementThreshold by default.