Home > Back-end >  Jetpack Compose Animation skips to target value immediately
Jetpack Compose Animation skips to target value immediately

Time:01-20

I'm trying to achieve a smooth animation of a simple round timer. Like this, but smoother timer

However it just skips to targetValue immediately and that's it there's no animation at all. I'm trying to do it like this:

@Composable
private fun SampleTimer(duration: Int, modifier: Modifier = Modifier) {
    var animatedPercentage by remember { mutableStateOf(1f) }
    LaunchedEffect(Unit) {
        animate(
            initialValue = 1f,
            targetValue = 0f,
            animationSpec = infiniteRepeatable(
                tween(
                    durationMillis = duration.seconds.inWholeMilliseconds.toInt(),
                    easing = LinearEasing,
                ),
            ),
        ) { value, _ ->
            animatedPercentage = value
        }
    }
    val arcColor = MaterialTheme.colors.primaryVariant
    Canvas(
        modifier = modifier,
    ) {
        drawArc(
            color = arcColor,
            useCenter = true,
            startAngle = -90f,
            sweepAngle = -360f * animatedPercentage,
        )
    }
}

Why does this happen, what am I missing here?

CodePudding user response:

You can use an Animatable state. The angle will animate from 0–360°.

Something like:

val angle = remember {
    Animatable(0f)
}
LaunchedEffect(angle) {
    launch {
        angle.animateTo(360f, animationSpec =
             infiniteRepeatable(
                tween(
                    durationMillis = 5000,
                    easing = LinearEasing,
                ),
            )
        )
    }
}

val arcColor = Red

Canvas(
    modifier = Modifier.size(100.dp),
) {
    drawArc(
        color = arcColor,
        useCenter = true,
        startAngle = -90f,
        sweepAngle = -angle.value,
    )
}

enter image description here

CodePudding user response:

The problem was that the animations were turned off in developer settings on my device, and I forgot that

  • Related