Animatable
@RememberInComposition
public fun Animatable(initialValue: Color): Animatable<Color, AnimationVector4D>
This Animatable
function creates a Color 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 via a CancellationException
.
Animatable
also supports animating data types other than Color
, such as Floats and generic
types. See androidx.compose.animation.core.Animatable
for other variants.
Parameters
initialValue | initial value of the Animatable |
Code Examples
AnimatableColor
fun AnimatableColor() {
@Composable
fun animate(
targetValue: Color,
animationSpec: AnimationSpec<Color>,
onFinished: (Color) -> Unit,
): Color {
// Creates an Animatable of Color, and remembers it.
val color = remember { Animatable(targetValue) }
val finishedListener = rememberUpdatedState(onFinished)
// Launches a new coroutine whenever the target value or animation spec has changed. This
// automatically cancels the previous job/animation.
LaunchedEffect(targetValue, animationSpec) {
color.animateTo(targetValue, animationSpec)
// Invokes finished listener. This line will not be executed if the job gets canceled
// halfway through an animation.
finishedListener.value(targetValue)
}
return color.value
}
}