I am trying to create an icon that will fade into ...
# compose
r
I am trying to create an icon that will fade into the screen for a few seconds and fade itself out. When the icon is replaced the previous one immediately disappears paving way for the new one to animate itself in and out. Here’s what I’ve come up with but I have a feeling there’s a better way of doing this. Code in 🧵
Copy code
/**
 *  This icon fades in and out after a delay whenever [icon] is changed
 *  but disappears immediately [icon] is replaced in the middle of an animation
 */
@Composable
private fun DisappearingIcon(
    icon: ImageVector,
    modifier: Modifier = Modifier,
    contentDescription: String,
    delay: Long
) {
    val alpha = Animatable(0f)

    val animationSpec = tween<Float>(500)

    LaunchedEffect(icon) {
        alpha.animateTo(1f, animationSpec = animationSpec)
        delay(delay)
        alpha.animateTo(0f, animationSpec = animationSpec)
    }

    Icon(
        imageVector = icon,
        modifier = modifier
            .graphicsLayer {
                this.alpha = alpha.value
            },
        contentDescription = contentDescription
    )
}
f
sorry, I sent to channel by mistake, didn't intend to
r
I don’t want to crossfade all the time. I want to preempt the currently running animation when a new icon arrives midway.
m
I don't see anything wrong with what you are doing here. I think i prefer to use the animate function instead:
Copy code
var alpha by remember { mutableStateOf(0f) }

LaunchedEffect(icon) {
    animate(
        initialValue = 0f,
        targetValue = 1f,
        animationSpec = tween(500)
    ) { value: Float, _: Float ->
        alpha = value
    }

    delay(delay)

    animate(
        initialValue = 1f,
        targetValue = 0f,
        animationSpec = tween(500)
    ) { value: Float, _: Float ->
        alpha = value
    }

}
But if you're going to use Animatable, you should probably put it in a remember.
i don't know if there's an advantage of your approach over mine, but either way I think is reasonable.
r
Is the
animate
function new cos I’ve never seen it before. It looks very clean, I’ll try that out