Thread
#compose
    j

    josefdolezal

    1 year ago
    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
    Rob Meeuwisse

    Rob Meeuwisse

    1 year ago
    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:
    @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

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