Reputation: 142
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?
Upvotes: 8
Views: 6515
Reputation: 1012
It's changed a bit, you have to use animateColorAsState
and set containerColor
to change background color by animation.
fun myButton(isButtonEnabled : Boolean) {
val animatedColor = animateColorAsState(
if (isButtonEnabled)
MaterialTheme.colorScheme.outline
else
MaterialTheme.colorScheme.primary
)
Button(
onClick = { //todo },
colors = ButtonDefaults.buttonColors(
containerColor = animatedColor.value, // your background color
contentColor = Color.Unspecified,
disabledContainerColor = Color.Unspecified,
disabledContentColor = Color.Unspecified
)
)
}
Upvotes: 1
Reputation: 406
You could try like this, set the button both background and disabled with the animated color
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")
}
Upvotes: 10
Reputation: 712
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)){}
Upvotes: 3