How to make text number animated when display in jetpack compose?
W

1

7

I want to show text with numbers and I wanted to achieve is to animate that text while displaying it. The animation is it should increase the counter from zero to the target value number. I tried using animateIntAsState but it's not working.

This is the state I tired :

 val daysCounter by animateIntAsState(
        targetValue = days ,
        animationSpec = tween(
            durationMillis = 5000,
            easing = FastOutSlowInEasing
        )
    )

And text :

        Text(
                text = "$daysCounter",
                fontSize = 40.sp,
                color = MaterialTheme.colors.onPrimary,
                fontWeight = FontWeight.Bold
            )
Wellman answered 5/2, 2022 at 17:5 Comment(0)
S
12

From animateIntAsState:

When the provided targetValue is changed, the animation will run automatically.

Your animation doesn't work because targetValue is static.

The first recomposition must be done with an initial value, and the next recomposition you can pass the target value. For example, you can use LaunchedEffect if you need to start the animation instantly(or with some delay) when the screen appears:

var days by remember { mutableStateOf(0) }
val daysCounter by animateIntAsState(
    targetValue = days,
    animationSpec = tween(
        durationMillis = 5000,
        easing = FastOutSlowInEasing
    )
)
LaunchedEffect(Unit) {
    days = 300
}

More info about animations in Compose can be found in documentation.

Senary answered 5/2, 2022 at 17:35 Comment(4)
can we have a double value with decimals animate like this?Christoper
@HarishPadmanabh you can animate float for sure, there's animateFloatAsState - since float is used in all places in Compose, it should be enough. you can also check out other functions animate*AsState, including basic animateValueAsState which will allow you animating any type at all - you just need to provide a way to convert it to vector of values to animate throughSenary
How can we the digits to scroll up and down in animationChristoper
Although this works totally fine in a running application or in an interactive mode, but it is not working in the "Start Animation Preview", may be because this is not an actual composition and the "LaunchedEffect" will not be triggered in this case.Roti

© 2022 - 2024 — McMap. All rights reserved.