我有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)
}
我在这里做错了什么吗?根据您的代码库,您在协程范围内调用animateTo
函数。注意,animateTo
函数是一个挂起函数。因此,bar2#animateTo
不会被执行,直到bar1#animateTo
被执行。
要让它们一起动画,你需要使用async-await (Ref: 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) }
)
}
您也可以通过为每个Animatable分别调用launch
来同时运行动画
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)}
}