Hey folks :spock-hand: , is there a way to animate...
# compose
j
Hey folks 🖖 , is there a way to animate
Buttons
colors based on
enabled
? What comes to my mind is to create my own class implementing
ButtonColors
which would then animate the color using
animateColorAsState
, but it seems a bit too verbose
r
That is how I did it. I wanted to take the isPressed state into account for the button colors, which definitely needs a custom ButtonColors instance. Remember to remember the new ButtonColor instance that you will create. I did this:
Copy code
@Composable
private fun rememberButtonColors(
    interactionSource: InteractionSource,
    backgroundColorPressed: Color,
    backgroundColorNormal: Color,
    contentColorPressed: Color,
    contentColorNormal: Color,
): ButtonColors = remember(
    interactionSource,
    backgroundColorPressed,
    backgroundColorNormal,
    contentColorPressed,
    contentColorNormal,
) {
    object : ButtonColors {
        private val isPressed
            @Composable get() = interactionSource.collectIsPressedAsState().value

        @Composable
        override fun backgroundColor(enabled: Boolean): State<Color> = animateColorAsState(...) // calc color dependant on state

        // etc.
    }
}
j
Thanks! Good to know I was not the only one exploring this approach 😅 I went with suboptimal solution and just
Crossfade
two buttons:
Copy code
@Composable
fun AnimatedButton(isEnabled: Boolean = true) = Crossfade(targetState = isEnabled) { isEnabled ->
    Button(enabled = isEnabled)
}