Android compose动画浮动相等测试

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

我正在尝试使用 android jetpack 撰写一个简单的项目。我有一个从 0 到 1 的动画浮动状态(使用

animateFloatAsState
),如下所示:

var xTarget by remember { mutableFloatStateOf(0F) }

val x: Float by animateFloatAsState(
        targetValue = xTarget,
        animationSpec = tween(durationMillis = xDuration, easing = xEasing),
        label = "x animation",
    ) {
        x -> when (x) {
           0 -> xTarget = 1
           1 -> xTarget = 0
        }
    }

通过设置

xTarget = 1
来触发动画的按钮。现在我想在 x = 0.5 时做出反应,如下所示:

 if (x == 0.5) Log.d(LOG_TAG, "Middle")

但我发现这是不可靠的 - 它不会在所有运行中执行 - 这可能是预期的,因为我们正在处理动画浮动的相等性。

您认为解决这个问题的最佳方法是什么?

我可以立即想到两种方法:1)测试一个小的间隔 - 但这并不理想,因为不可靠和提供大量点击之间的界限很明显并且取决于动画的速度。 2)类似

var isRightTested : Boolean by remember { mutableStateOf(false) }

if (x>0.5 && !isRightTested || x < 0.5 && isRightTested) { 
        isRightTested = !isRightTested
        // TODO
}

这似乎太复杂了(编辑 - 现在更加简洁,请参阅下面我的评论)。

android android-animation android-compose
1个回答
0
投票

如果您需要 x:

,您是否尝试过此操作?
var xTarget by remember { mutableFloatStateOf(0F) }

val x: Float by animateFloatAsState(
    targetValue = xTarget,
    animationSpec = tween(durationMillis = xDuration, easing = xEasing),
    label = "x animation",
) {
    x -> when (x) {
       0 -> xTarget = 1
       0.5 -> xTarget = 0.5   // add this line for 0.5
       1 -> xTarget = 0
       in 0f..0.5f -> xTarget = 1   // add this if you need a range (0f - 0.5f)
    }
}

如果您需要使动画向上/向下跳跃,您也可以在 xEasing 的 when 语句中添加这些


我看到当 x 为 0 时,您正在将 xTarget 更改为 1;当 x 为 1 时,您正在将 xTarget 更改为 0。如果您想要无限动画,您也可以使用如下所示的内容:

val infiniteTransition = rememberInfiniteTransition(label = "")
val alpha by infiniteTransition.animateFloat(
    initialValue = 1.0f, targetValue = 0.0f, animationSpec = infiniteRepeatable(
        animation = keyframes {
            durationMillis = 3000
            0.0f at 0 with LinearOutSlowInEasing   // or your custom easing
            1.0f at 500 with LinearOutSlowInEasing
            0.0f at 1000 with LinearOutSlowInEasing
            1.0f at 1500 with LinearOutSlowInEasing
            0.0f at 2000 with LinearOutSlowInEasing
            1.0f at 2500 with LinearOutSlowInEasing
            0.0f at 3000 with LinearOutSlowInEasing
        },
        repeatMode = RepeatMode.Restart,
    ), label = ""
)

上面的代码会给你类似光标的闪烁行为。并且每 3000ms 就会重复一次

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