How do I create a bounce animation? I want to scal...
# compose
a
How do I create a bounce animation? I want to scale some text to 1.2 and then back to 1.0, with spring animation both ways.
I currently have something like this:
Copy code
var bounce by remember{ mutableStateOf(false) }
Button(onClick = { bounce = true })
val scale by animateFloatAsState(
    targetValue = if (bounce) 1.2f else 1.0f,
    finishedListener = {
        bounce = false
    }
}
Text("Text", modifier = Modifier.scale(scale))
The problem is that if the button is pressed exactly as the scale reaches 1.2f, what happens is the
finishedListener
is called and sets
bounce=false
and immediately after that
onClick
is called and sets
bounce=true
. Since scale is already at 1.2, it gets stuck there.
y
a
animation spec only controls how the value transitions from current to the target
f
I've never actually used it but it looks like you need
Animatable
. It has
suspend animateTo()
function so in your case you could write something like this:
Copy code
scope.launch {
  bounce.animateTo(1.2f)
  bounce.animateTo(1f)
}
a
Thanks, I’ll take a look at
Animatable
f
👋 Did
Animatable
work out for you?
☝️ 1
a
Yes, worked great, thanks:
Copy code
val scale = remember { Animatable(1.0f) }
    val coroutineScope = rememberCoroutineScope()
    if (highlight){
        coroutineScope.launch {
            val animationSpec = spring<Float>(
                dampingRatio = Spring.DampingRatioLowBouncy,
                stiffness = (0.9f * Spring.StiffnessMedium + 0.1f * Spring.StiffnessHigh)
            )
            scale.animateTo(1.1f, animationSpec = animationSpec)
            scale.animateTo(1.0f, animationSpec = animationSpec)
        }
    }
    Text(
        text = text,
        color = MaterialTheme.colors.error,
        style = MaterialTheme.typography.caption,
        modifier = Modifier.scale(scale.value)
    )
🎉 1