如何在没有onActive的情况下自动启动动画,并设置animatedFloatAsState的初始值

Ely*_*lye 2 android android-jetpack-compose

在过去(在 alpha11 之前),我可以在触发可组合函数时将值从 0 动画化到 1,如下所示,我可以在其中设置initialValueonActive使用aniumateTo.

val animatedProgress = animatedFloat(0f)
onActive {
    animatedProgress.animateTo(
        targetValue = 1f,
        anim = infiniteRepeatable(
            animation =
                tween(durationMillis = 2000, easing = LinearEasing),
        )
    )
}

val t = animatedProgress.value
Run Code Online (Sandbox Code Playgroud)

initialValue但是,现在在 alpha13 中,我找不到设置, 或 的方法animateTo。现在也已onActive弃用。

我编码如下

    val floatAnimation = animateFloatAsState(
        targetValue = 1f,
        animationSpec = infiniteRepeatable(
            animation = tween(durationMillis = 2000, easing = LinearEasing),
        )
    )
Run Code Online (Sandbox Code Playgroud)

我怎么能够...

  • 设置初始值为0
  • 开始动画(不需要状态布尔值来启动它)
  • 重复从 0 到 1 进行动画处理

Gab*_*tti 5

您可以使用AnimatableAPI 和LaunchedEffect可组合项。您不需要布尔值来启动动画。

就像是:

val animatedAlpha = remember { Animatable(0f) }

Box(
    Modifier
        .background(color = (Color.Blue.copy(alpha = animatedAlpha.value)))
        .size(100.dp,100.dp)

)

LaunchedEffect(animatedAlpha) {
    animatedAlpha.animateTo(1f,
        animationSpec = infiniteRepeatable(
            animation = tween(durationMillis = 2000, easing = LinearEasing)
        ))
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述