Jetpack 像 Valueanimator 一样使用 vararg 值编写动画 animateFloatAsState

问题描述 投票:0回答:2

我希望实现一个改变比例值的动画来提醒用户可以点击某个小部件。以前我可以用

Valueanimator
:

ValueAnimator.ofFloat(0.8f,0.5f,0.8f,1.2f,0.6f,0.8f) //animateFloatAsState only support to define target value,init value

在jetpack compose中,我不得不想出这个实现

    val animate = remember { Animatable(0.8f) }

    val playCheckItemAnimation = {
        scope.launch {
            animate.stop()
            for (i in 0..2) {
                animate.animateTo(0.8f)
                animate.animateTo(0.5f)
                animate.animateTo(0.8f)
                animate.animateTo(1.2f)
                animate.animateTo(0.6f)
                animate.animateTo(0.8f)
            }
        }
    }

如果我需要像

ValueAnimator.ofFloat(0.8f,0.5f,0.8f,1.2f,0.6f,0.8f)
那样设置一组浮动,似乎没有方便的方法。 有没有简单的方法可以做到这一点?

android-jetpack android-jetpack-compose
2个回答
1
投票

您可以使用

rememberInfiniteTransition
。在文档

中查看有关动画的更多信息
val infiniteTransition = rememberInfiniteTransition()
val value by infiniteTransition.animateFloat(
    initialValue = 0.5f,
    targetValue = 0.8f,
    animationSpec = infiniteRepeatable(
        animation = tween(durationMillis = AnimationConstants.DefaultDurationMillis),
        repeatMode = RepeatMode.Reverse
    )
)

Box(
    Modifier
        .padding(10.dp)
        .size(100.dp)
        .alpha(value)
        .background(Color.Red)
)


0
投票

这个 API 不存在,但你可以自己构建一个相对简单的:

suspend fun <T, D : AnimationVector> Animatable<T, D>.animateTo(
    vararg value: T,
) {
    value.forEach {
        this.animateTo(
            targetValue = it,
            animationSpec = animationSpec
        )
    }
}

用法

val scope = rememberCoroutineScope()
val animate = remember { Animatable(0.8f) }
val playCheckItemAnimation = {
    scope.launch {
        animate.stop()
        repeat(2) {
            animate.animateTo(0.8f, 0.5f, 0.8f, 1.2f, 0.6f, 0.8f)
        }
    }
}

您也可以轻松地向

animateTo
添加额外的参数,例如
animationSpec
等。

© www.soinside.com 2019 - 2024. All rights reserved.