kotlin - 如何在 Jetpack Compose 中启动和停止动画

标签 kotlin animation android-jetpack-compose

在 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/

相关文章:

android - 0dp 大小的可组合项甚至可以组合吗

android - Kotlin 记录器 - 记录到文件

android - 如何更改 kotlin fragment 类中的 ActionBar 标题?

android - 如何在 Android Studio 中为 Jetpack Compose UI 启用交互式预览按钮?

再次调用 onCreate 时 Android 动画不启动

在交互式 shell 中运行时与 pygame 一起使用时,Python.exe 没有响应

android - @composable 调用只能在 @composable 函数的上下文中发生

android - UNINITIALIZED VARIABLE 必须初始化变量 _longPressed

intellij-idea - 无法解析符号 kotlinOptions(在 Gradle 版本中)

java - 时间线的默认帧速率是多少?