import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import kotlin.random.Random
@Composable
fun ColorBoxAnimationScreen() {
val colors = listOf(Color.Red, Color.Green, Color.Blue, Color.Yellow, Color.Cyan, Color.Magenta)
var currentColor by remember { mutableStateOf(Color.Red) }
val animatedColor by animateColorAsState(targetValue = currentColor)
Box(
modifier = Modifier
.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier
.size(150.dp)
.background(animatedColor)
)
Spacer(modifier = Modifier.height(24.dp))
Button(onClick = {
// Pick a new random color different from current
var newColor: Color
do {
newColor = colors[Random.nextInt(colors.size)]
} while (newColor == currentColor)
currentColor = newColor
}) {
Text("Change Color")
}
}
}
}This screen shows a square box whose background color changes smoothly when you tap the button below it.
We keep track of the current color using a mutableStateOf. When the button is clicked, we pick a new random color from a predefined list, making sure it is different from the current color.
The animateColorAsState function takes the current color as its target and returns an animated color value that changes smoothly over time. We use this animated color as the background color of the box.
The UI is centered using a Box with contentAlignment and a Column to stack the box and button vertically.