Animations in Compose
animate*AsState, AnimatedVisibility & updateTransition
Compose animates by re-targeting a value: you change a state, and a backing `Animatable` smoothly moves to the new value on every frame. No manual ValueAnimators or XML.
๐ Explanation
Animation in Compose is declarative: `animateDpAsState` (and its color/float/size siblings) take a `targetValue` and quietly run an `Animatable` toward it whenever that target changes โ you read the animated value and Compose recomposes each frame. `updateTransition` groups several animated values under one state so they stay in sync. `AnimatedVisibility` handles the harder case of animating composition itself, running `enter`/`exit` specs as content is added or removed from the tree.
Note: Code execution is not available for Android/Kotlin in the browser. Use Android Studio to run and test the app.
import androidx.compose.animation.AnimatedVisibilityimport androidx.compose.animation.animateColorAsStateimport androidx.compose.animation.core.animateDpAsStateimport androidx.compose.animation.core.tweenimport androidx.compose.animation.core.updateTransitionimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.material3.*import androidx.compose.runtime.*import androidx.compose.ui.graphics.Colorimport androidx.compose.ui.unit.dp@Composablefun ExpandableCard(title: String, body: String) {var expanded by remember { mutableStateOf(false) }// 1. Single-value animations: just animate*AsStateval elevation by animateDpAsState(targetValue = if (expanded) 12.dp else 1.dp,animationSpec = tween(durationMillis = 300),label = "elevation")// 2. Coordinate several values that share one driverval transition = updateTransition(expanded, label = "card")val containerColor by transition.animateColor(label = "color") { isOpen ->if (isOpen) Color(0xFFE0F2F1) else Color.White}Card(onClick = { expanded = !expanded },colors = CardDefaults.cardColors(containerColor = containerColor),elevation = CardDefaults.cardElevation(defaultElevation = elevation)) {Text(title)// 3. Animate appearance/disappearance of contentAnimatedVisibility(visible = expanded,enter = fadeIn(),exit = fadeOut()) {Text(body)}}}