Reputation: 60251
In the past (before alpha11), I can animate a value from 0 to 1 upon triggering the composable function as below, where I can set initialValue
and also have onActive
with aniumateTo
.
val animatedProgress = animatedFloat(0f)
onActive {
animatedProgress.animateTo(
targetValue = 1f,
anim = infiniteRepeatable(
animation =
tween(durationMillis = 2000, easing = LinearEasing),
)
)
}
val t = animatedProgress.value
However, now in alpha13, I cannot find a way to set initialValue
, or animateTo
. The onActive
is also now deprecated.
I coded as below
val floatAnimation = animateFloatAsState(
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = tween(durationMillis = 2000, easing = LinearEasing),
)
)
How can I...
Upvotes: 3
Views: 2778
Reputation: 364730
You can use the Animatable
API and the LaunchedEffect
composable. You don't need a boolean to start the animation.
Something like:
val animatedAlpha = remember { Animatable(0f) }
Box(
Modifier
.background(color = (Color.Blue.copy(alpha = animatedAlpha.value)))
.size(100.dp,100.dp)
)
LaunchedEffect(animatedAlpha) {
animatedAlpha.animateTo(1f,
animationSpec = infiniteRepeatable(
animation = tween(durationMillis = 2000, easing = LinearEasing)
))
}
Upvotes: 7
Reputation: 60251
Looks like I have to use a boolean to change the state and use LaunchEffect
to start and change the state as below.
var start by remember{ mutableStateOf(false) }
val floatAnimation = animateFloatAsState(
targetValue = if (start) 1f else 0f,
animationSpec = infiniteRepeatable(
animation = tween(durationMillis = 2000, easing = LinearEasing),
)
)
LaunchedEffect(true) {
start = true
}
val t = floatAnimation.value
Not sure if this is the best way to code around it.
Upvotes: 1