如何使按钮背景颜色在“启用”更改时动画变化?

lux*_*i78 7 android-jetpack-compose

假设有一个按钮定义如下

val btnEnabled by remember { mutableStateOf(true) }

...

Button(
  colors = ButtonDefaults.buttonColors(
    background = Color.Yellow
    disabledBackgroundColor = Color.Black ),
  enabled = btnEnabled

) {
...
}

Run Code Online (Sandbox Code Playgroud)

当 的值btnEnabled改变时,按钮的背景会立即刚性地改变。有什么办法让它变成动画过渡吗?

axe*_*ans 10

您可以尝试这样,将按钮设置为背景并使用动画颜色禁用

val isButtonEnabled = remember { mutableStateOf(true) }
val animatedButtonColor = animateColorAsState(
    targetValue = if (isButtonEnabled.value) Color.Green else Color.Red,
    animationSpec = tween(1000, 0, LinearEasing)
)

Button(
    colors = ButtonDefaults.buttonColors(
        backgroundColor = animatedButtonColor.value,
        disabledBackgroundColor = animatedButtonColor.value,
    ),
    enabled = isButtonEnabled.value,
    onClick = { }
) {
    Text(text = "Target")
}

Run Code Online (Sandbox Code Playgroud)