简体   繁体   中英

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

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.

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM