https://kotlinlang.org logo
#compose
Title
# compose
j

josefdolezal

09/03/2021, 9:05 PM
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

Rob Meeuwisse

09/05/2021, 6:39 PM
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

josefdolezal

09/10/2021, 9:07 PM
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)
}
3 Views