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
            )
Himanshi
  • 84
  • 1
  • 2
  • 13
Jeevan Rupacha
  • 3,055
  • 1
  • 15
  • 29

1 Answers1

10

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.

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
  • can we have a double value with decimals animate like this? – Harish Padmanabh Aug 18 '23 at 21:08
  • @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 through – Phil Dukhov Aug 19 '23 at 02:55
  • How can we the digits to scroll up and down in animation – Harish Padmanabh Aug 21 '23 at 08:01