Jetpack Compose 中多个动画未同时启动

And*_*Dev 1 android kotlin android-studio android-jetpack-compose jetpack-compose-animation

我有 3 个动画,但最上面的一个先启动,然后是另外两个,如何让它们同时启动?我尝试将它们放在相同的协程作用域中,但仍然得到相同的结果。

LaunchedEffect(isItemInView) {
    scope.launch {
        coroutineScope {
            launch { // Even without the scope.launch, coroutineScope, launch lines, same effect
                bar1.animateTo(if (isItemInView) bar1EndLocation else bar1StartLocation)
                bar2.animateTo(if (isItemInView) bar2EndSize else bar2StartSize)
                bar3.animateTo(if (isItemInView) bar3EndSize else bar3StartSize)
            }
        }

    }
}
Column{
   Bar1(modifier = Modifier.offset(bar1.value.x.dp, bar1.value.y.dp)
   Bar2(modifier = Modifier.size(bar2.value.width.dp, bar2.value.height.dp)
   Bar3(modifier = Modifier.size(bar3.value.width.dp, bar3.value.height.dp)
}
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么吗?

Ash*_*hok 5

根据您的代码库,您正在animateTo协程范围内调用该函数。请注意,该animateTo函数是一个挂起函数。结果,直到执行后bar2#animateTo才会执行。bar1#animateTo

要将它们全部动画在一起,您需要使用 async-await (参考: https: //stackoverflow.com/a/57458479/5309486

launch {
    awaitAll(
        async { bar1.animateTo(if (isItemInView) bar1EndLocation else bar1StartLocation) }
        async { bar2.animateTo(if (isItemInView) bar2EndSize else bar2StartSize) }
        async { bar3.animateTo(if (isItemInView) bar3EndSize else bar3StartSize) }
    )
}

Run Code Online (Sandbox Code Playgroud)


Thr*_*ian 5

launch您还可以通过单独调用每个 Animatable 来同时运行动画

LaunchedEffect(key1 = isItemInView) {
    launch { bar1.animateTo(if (isItemInView) bar1EndLocation else bar1StartLocation) }
    launch { bar2.animateTo(if (isItemInView) bar2EndSize else bar2StartSize) }
    launch { bar3.animateTo(if (isItemInView) bar3EndSize else bar3StartSize)}
}
Run Code Online (Sandbox Code Playgroud)