animateDpAsState

Functions summary

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

Fire-and-forget animation function for Dp.

Cmn

Functions

@Composable
fun animateDpAsState(
    targetValue: Dp,
    animationSpec: AnimationSpec<Dp> = dpDefaultSpring,
    label: String = "DpAnimation",
    finishedListener: ((Dp) -> Unit)? = null
): State<Dp>

Fire-and-forget animation function for Dp. This Composable function is overloaded for different parameter types such as Float, Color, 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.

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

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

import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp

@Composable
fun HeightAnimation(collapsed: Boolean) {
    // Animates a height of [Dp] type to different target values based on the [collapsed] flag.
    val height: Dp by animateDpAsState(if (collapsed) 10.dp else 20.dp)
    Box(Modifier.fillMaxWidth().requiredHeight(height).background(color = Color.Red))
}
Parameters
targetValue: Dp

Target value of the animation

animationSpec: AnimationSpec<Dp> = dpDefaultSpring

The animation that will be used to change the value through time. Physics animation will be used by default.

label: String = "DpAnimation"

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

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

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

Returns
State<Dp>

A State object, the value of which is updated by animation.