[英]value not updating (Jetpack Compose)
我正在尝试根据自己的需要调整视频教程。 基本上,我有一个框列表,我希望每个框都以 1 秒的延迟进行动画处理。 我不明白为什么我的代码不起作用。 这
延迟值
似乎没有更新。 有任何想法吗?
@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
}
}
}
当在可组合项中记住的 state 发生更改时,整个可组合项都会重新组合。
所以要达到给定的要求,
我们可以简单地使用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
}
使用 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.