[英]value not updating (Jetpack Compose)
I'm trying to adapt a video tutorial to my own needs.我正在尝试根据自己的需要调整视频教程。 Basically, I have a list of boxes and I want each one to animate with a delay of 1 second after the other.
基本上,我有一个框列表,我希望每个框都以 1 秒的延迟进行动画处理。 I don't understand why my code does not work.
我不明白为什么我的代码不起作用。 The
这
delay.value
延迟值
does not appear to update.似乎没有更新。 Any ideas?
有任何想法吗?
@Composable
fun Rocket(
isRocketEnabled: Boolean,
maxWidth: Dp,
maxHeight: Dp
) {
val modifier: Modifier
val delay = remember { mutableStateOf(0) }
val tileSize = 50.dp
if (!isRocketEnabled) {
Modifier.offset(
y = maxHeight - tileSize,
)
} else {
val infiniteTransition = rememberInfiniteTransition()
val positionState = infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 2000,
delayMillis = delay.value,
easing = LinearEasing
)
)
)
modifier = Modifier.offset(
x = (maxWidth - tileSize) * positionState.value,
y = (maxHeight - tileSize) - (maxHeight - tileSize) * positionState.value,
)
listOf(
Color(0xffDFFF00),
Color(0xffFFBF00),
Color(0xffFF7F50),
Color(0xffDE3163),
Color(0xff9FE2BF),
Color(0xff40E0D0),
Color(0xff6495ED),
Color(0xffCCCCFF),
).forEachIndexed { index, color ->
Box(
modifier = modifier
.width(tileSize)
.height(tileSize)
.background(color = color)
)
delay.value += 1000
}
}
}
When a state remembered in a composable is changed, the entire composable gets re-composed.当在可组合项中记住的 state 发生更改时,整个可组合项都会重新组合。
So to achieve the given requirement,所以要达到给定的要求,
Instead of using a delay as a mutableState
we can simply use an Int
delay and update its value in the forEach
loop and create an animation with the updated delay.我们可以简单地使用
Int
延迟并在forEach
循环中更新其值,并使用更新的延迟创建 animation,而不是使用延迟作为mutableState
。
.forEachIndexed { index, color ->
Box(
modifier = createModifier(maxWidth, maxHeight, tileSize, createAnim(delay = delay))
.width(tileSize)
.height(tileSize)
.background(color = color)
)
delay += 1000
}
Create the modifier with animation:-使用 animation 创建修饰符:-
fun createModifier(maxWidth: Dp, maxHeight: Dp, tileSize: Dp, positionState: State<Float>): Modifier {
return Modifier.offset(
x = ((maxWidth - tileSize) * positionState.value),
y = ((maxHeight - tileSize) - (maxHeight - tileSize) * positionState.value),
)
}
@Composable
fun createAnim(delay: Int): State<Float> {
val infiniteTransition = rememberInfiniteTransition()
return infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 2000,
delayMillis = delay,
easing = LinearEasing
)
)
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.