如何使按钮背景颜色在"enabled"变化时动画变化?



假设有一个按钮定义如下

val btnEnabled by remember { mutableStateOf(true) }
...
Button(
colors = ButtonDefaults.buttonColors(
background = Color.Yellow
disabledBackgroundColor = Color.Black ),
enabled = btnEnabled
) {
...
}

btnEnabled的值发生变化时,按钮的背景将立即发生剧烈变化。有没有办法让它变成动画过渡?

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

val isButtonEnabled = remember { mutableStateOf(true) }
val aniamtedButtonColor = 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")
}

您可以使用

val animatedColor = animateColorAsState(
if (btnEnabled.value) Color.Green else Color.Red )
Button(Modifier.background(animatedColor)){}

或者,如果你想控制更多的选项,比如持续时间;

val transitionState = remember {
MutableTransitionState(btnEnabled.value).apply {
targetState = !btnEnabled.value
}
}
val transition = updateTransition(transitionState, label = "transition")
val bgColorTransition by transition.animateColor(
label = "colorTransition",
transitionSpec = { tween(durationMillis = ANIMATION_DURATION) },
targetValueByState = {
if (btnEnabled.value) Color.Green else Color.Red
}
)
Button(Modifier.background(bgColorTransition)){}

相关内容

  • 没有找到相关文章

最新更新