How can I an animation on boolean change with jetpack compose?

1k Views Asked by At

Question

How can I achieve something like a wiggle animation with jetpack compose when a boolean is changing? From my understanding the library only supports transition animations or infinite animations. However in my case no composable object is actually changing their target value in anyway. In the examples that I found one always needs to change the target value, to actually see an animation. Like this

var isError by remember { mutableStateOf(false) }
val offset = animateIntAsState(if (isError) $targetValue else 0)
// Then have something that uses the offset and add a button that is changing the state of isError

However I don't want the targetValue to be different from what it initially was. I just want to see a keyframes animation for example.

1

There are 1 best solutions below

3
On

To achieve this you can use the finishedListener parameter that comes with all animateXAsState functions to switch the state which triggers the animation.

Example below which adds one line to your code snippet:

var animationState by remember { mutableStateOf(false) }
val xOffset: Dp by animateDpAsState(
    targetValue = if (animationState) 16.dp else 0.dp,
    finishedListener = { animationState = false }   // Add this
)