在 Jetpack Compose 中,我需要在单击文本时开始旋转文本。协程运行,完成后,动画应该停止。
到目前为止我已经:
var isRotating by remember { mutableStateOf(false) }
val angle = animateFloatAsState(
targetValue = if (isRotating) 360f else 0f,
animationSpec = infiniteRepeatable(tween(2000, easing = LinearEasing))
)
Box(
modifier = Modifier
.graphicsLayer { rotationZ = angle.value }
.clickable {
isRotating = true
coroutineScope.launch {
doSlowProcess()
isRotating = false
}
}
) {
Text("START")
}
文本“START”应该旋转,直到“doSlowProcess”运行。它开始旋转,但当它结束时,它并没有停止,只是开始以另一种方式旋转,速度较慢,当到达0°时,它翻转180度,然后继续。如果我再次单击它,它会进行正确的旋转,但在 0° 时会向前跳跃 90°。我想如果当“isRotating”变为 false 时旋转停止,这些“异常”就会消失。如何正确启动和停止旋转?
最佳答案
您可以使用不同的东西:
var isRotating by remember { mutableStateOf(false) }
val angle = remember {
Animatable(0f)
}
LaunchedEffect(isRotating) {
launch {
if (isRotating) {
angle.animateTo(
targetValue = 360f,
animationSpec = infiniteRepeatable(
tween(2000, easing = LinearEasing)
)
)
}
}
}
关于kotlin - 如何在 Jetpack Compose 中启动和停止动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74903014/