Animations make apps feel alive and smooth. animate*AsState helps you easily add simple animations to your app without complex code.
0
0
Animation basics (animate*AsState) in Android Kotlin
Introduction
When you want a button to smoothly change color when clicked.
When you want to animate the size of a box as the user interacts.
When you want to fade in or fade out a component smoothly.
When you want to animate a position or offset change in your UI.
Syntax
Android Kotlin
val animatedValue by animateFloatAsState(targetValue = someFloatValue) // or for colors val animatedColor by animateColorAsState(targetValue = someColorValue)
animate*AsState functions return a State that updates smoothly to the target value.
You use by keyword to get the current animated value easily.
Examples
This animates the transparency from fully visible (1f) to invisible (0f) based on
visible.Android Kotlin
val animatedAlpha by animateFloatAsState(targetValue = if (visible) 1f else 0f)
This smoothly changes the color between red and gray depending on
selected.Android Kotlin
val animatedColor by animateColorAsState(targetValue = if (selected) Color.Red else Color.Gray)
Sample App
This example shows a square box that changes color from red to green and grows in size when you tap it. Tapping again reverses the animation.
Android Kotlin
import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp @Composable fun AnimateAsStateExample() { var selected by remember { mutableStateOf(false) } val animatedColor by animateColorAsState( targetValue = if (selected) Color.Green else Color.Red ) val animatedSize by animateFloatAsState( targetValue = if (selected) 150f else 100f ) Box( modifier = Modifier .size(animatedSize.dp) .background(animatedColor) .clickable { selected = !selected } ) }
OutputSuccess
Important Notes
Use animate*AsState for simple, one-value animations.
Animations run automatically when the target value changes.
For more complex animations, consider Animatable or Transition.
Summary
animate*AsState lets you animate simple values easily.
Use it to smoothly change colors, sizes, positions, or other values.
Just change the target value and the animation happens automatically.