How to make button background color change animatedly when "enabled" changes?

Viewed 100

Suppose there's an button defined as follows

val btnEnabled by remember { mutableStateOf(true) }

...

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

) {
...
}

When the value of btnEnabled is changed, the button's background will immediately change rigidly. Any way to make it an animated transition?

2 Answers

You could try like this, set the button both background and disabled with the animated color

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")
}

You can use the

  val animatedColor = animateColorAsState(
    if (btnEnabled.value) Color.Green else Color.Red )

Button(Modifier.background(animatedColor)){}

Or if you want to control over more options like duration;

 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)){}
Related