【问题标题】:Jetpack Compose animateFLoatAsState replaced by Transition.animateFloat is not workingJetpack Compose animateFloatAsState 替换为 Transition.animateFloat 不起作用
【发布时间】:2022-11-10 16:57:51
【问题描述】:

你能告诉我为什么当我使用val animateAngle: Float by transition.animateFloat 而不是val animateAngle by animateFloatAsState 时它会停止工作吗?

单击按钮时,变量rotated 似乎没有更新。


    var rotated by remember {
        mutableStateOf(false)
    }

    val transition = updateTransition(
        targetState = rotated,
        label = "Rotate"
    )

        val animateAngle: Float by transition.animateFloat(
            transitionSpec = {
                tween(2000)
            },
            label = "Rotate box"
        ) { state ->
            when(state){
                rotated -> 360f
                else -> 0f
            }

        }

        Column (
        ) {
            Image(
                painter = painterResource(id = R.drawable.propeller),
                contentDescription = "fan",
                modifier = Modifier
                    .rotate(animateAngle)
                    .padding(30.dp)
                    .size(100.dp))

            Button(
                onClick = {
                    rotated = !rotated
                },
            ) {
                Text(text = "Rotate Box")
            }
        }

【问题讨论】:

    标签: android function android-jetpack-compose jetpack-compose-animation


    【解决方案1】:

    您有一个 boolean mutableState 用作目标状态对于您的过渡,truefalse 将是其目标状态。

    val transition = updateTransition(
        targetState = rotated,
        label = "Rotate"
    )
    

    现在您正在阅读 boolean mutableStatetargetValueByState lambda

    when(state) {
        rotated -> 360f
        else -> 0f
    }
    

    因为你正在那里阅读它,动画角度无论是true 还是false,总是会得到360f 的值。

    记录下来,

    Log.e("AnimatedAngle", "$animateAngle : Rotated boolean state [$rotated]")
    

    印刷:

    360.0 : Rotated boolean state [false]
    360.0 : Rotated boolean state [true]
    

    只需简单地删除它并以这种方式稍微修改targetValueByState 块,您的动画就可以工作了。

    val animateAngle: Float by transition.animateFloat(
          transitionSpec = {
              tween(2000)
          },
          label = "Rotate box"
    ) { state ->
          if (state) 360f else 0f
    }
    

    【讨论】:

      猜你喜欢
      • 2022-07-29
      • 1970-01-01
      • 2023-01-22
      • 2021-08-14
      • 2021-09-27
      • 1970-01-01
      • 2022-10-19
      • 2021-12-24
      • 1970-01-01
      相关资源
      最近更新 更多