animateColorAsState

Functions summary

State<Color>
@Composable
animateColorAsState(
    targetValue: Color,
    animationSpec: AnimationSpec<Color>,
    label: String,
    finishedListener: ((Color) -> Unit)?
)

Fire-and-forget animation function for Color.

Cmn

Functions

animateColorAsState

@Composable
fun animateColorAsState(
    targetValue: Color,
    animationSpec: AnimationSpec<Color> = colorDefaultSpring,
    label: String = "ColorAnimation",
    finishedListener: ((Color) -> Unit)? = null
): State<Color>

Fire-and-forget animation function for Color. This Composable function is overloaded for different parameter types such as Dp, Float, Int, Size, Offset, etc. When the provided targetValue is changed, the animation will run automatically. If there is already an animation in-flight when targetValue changes, the on-going animation will adjust course to animate towards the new target value.

animateColorAsState returns a State object. The value of the state object will continuously be updated by the animation until the animation finishes.

Note, animateColorAsState cannot be canceled/stopped without removing this composable function from the tree. See Animatable for cancelable animations.

import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color

@Composable
fun ColorAnimation(primary: Boolean) {
    // Animates to primary or secondary color, depending on whether [primary] is true
    // [animateState] returns the current animation value in a State<Color> in this example. We
    // use the State<Color> object as a property delegate here.
    val color: Color by
        animateColorAsState(
            if (primary) MaterialTheme.colors.primary else MaterialTheme.colors.secondary
        )
    Box(modifier = Modifier.background(color))
}
Parameters
targetValue: Color

Target value of the animation

animationSpec: AnimationSpec<Color> = colorDefaultSpring

The animation that will be used to change the value through time, spring by default

label: String = "ColorAnimation"

An optional label to differentiate from other animations in Android Studio.

finishedListener: ((Color) -> Unit)? = null

An optional listener to get notified when the animation is finished.