I am currently working on a soundboard app. When I press one a button corresponding to a particular sound I would like an image to appear spin around a few times and then disappear all based on 1 button press. I have been able to tackle the appearing and spinning around I think. However, I cannot get the image to then disappear without pressing the button again. I am hoping there is something I am missing in the Jetpack Compose animation API that would allow me to easily do this without having to write up a custom function of some sort.
I have gone through some tutorials online and watched Philipp Lackner's video on Compose animations. I have experimented with AnimatedVisibility, AnimatedContent, and animateFloatAsState but they all still result in a visible image after I press the button. I have also tried to change the animationSpec property using tween, repeatable, and keyframes but again I always end up with a visible image after the animation is finished.
I have included an example of something I have tried below so you can get an idea of what I am doing.
var isVisible by remember {
    mutableStateOf(false)
   }
Button(onClick = {
         isVisible = !isVisible
    }) {
       Text("Toggle")
      }
val alpha by animateFloatAsState(
     targetValue = if (isVisible) 1f else 0f,
     animationSpec = repeatable(2, 
     animation = tween(5000), repeatMode = RepeatMode.Reverse)
    ,label = "label")
Box(
  Modifier
     .fillMaxWidth()
     .height(100.dp)
     .graphicsLayer(alpha = alpha)
     .background(Color.Red))
Using something like the following might help if you know the duration you'd like the image to persist for. I've just made this for an onboarding fade in/out animation. This uses AnimatedVisibility rather than animating the alpha value directly.
    var isVisible by remember { mutableStateOf(false) }
    AnimatedVisibility(
        visible = isVisible,
        enter = fadeIn(tween(3000)),
        exit = fadeOut(tween(3000)),
    ) {
        Box(
            Modifier
                .fillMaxWidth()
                .height(100.dp)
                .background(Color.Red)
        )
    }
    Button(onClick = {
        isVisible = true
    }) {
        Text("Toggle")
    }
    LaunchedEffect(isVisible) {
        if (isVisible) {
            delay(3000L) // however long you want the animation to run
            isVisible = false
        }
    }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With