Jetpack compose animation animateFloatAsState with vararg value like Valueanimator

Viewed 1812

I hope to implement an animation that change scale value to remind the user that a widget can be clicked. In the past, I could use Valueanimator:

ValueAnimator.ofFloat(0.8f,0.5f,0.8f,1.2f,0.6f,0.8f) //animateFloatAsState only support to define target value,init value

In jetpack compose,I had to came up with this implementation

    val animate = remember { Animatable(0.8f) }

    val playCheckItemAnimation = {
        scope.launch {
            animate.stop()
            for (i in 0..2) {
                animate.animateTo(0.8f)
                animate.animateTo(0.5f)
                animate.animateTo(0.8f)
                animate.animateTo(1.2f)
                animate.animateTo(0.6f)
                animate.animateTo(0.8f)
            }
        }
    }

If I need to set a group of float like ValueAnimator.ofFloat(0.8f,0.5f,0.8f,1.2f,0.6f,0.8f),there seems to be no convenient way. Is there a simple way to do this?

1 Answers

You can use rememberInfiniteTransition. Check out more about animations in documentation

val infiniteTransition = rememberInfiniteTransition()
val value by infiniteTransition.animateFloat(
    0.5f,
    0.8f,
    animationSpec = infiniteRepeatable(
        animation = tween(durationMillis = AnimationConstants.DefaultDurationMillis),
        repeatMode = RepeatMode.Reverse
    )
)
Box(
    Modifier
        .padding(10.dp)
        .size(100.dp)
        .alpha(value)
        .background(Color.Red)
)

Related