在 Jetpack Compose 中显示时如何使文本编号动画化?

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

我想显示带有数字的文本,我想实现的是在显示文本时为该文本设置动画。动画是它应该将计数器从零增加到目标值数字。我尝试使用 animateIntAsState 但它不起作用。

这是我累的状态:

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

和文字:

        Text(
                text = "$daysCounter",
                fontSize = 40.sp,
                color = MaterialTheme.colors.onPrimary,
                fontWeight = FontWeight.Bold
            )

来自animateIntAsState

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

您的动画不起作用,因为 targetValue 是静态的。

第一次重组必须带初始值,下次重组可以传入目标值。例如,如果您需要在屏幕出现时立即(或延迟)启动动画,则可以使用 LaunchedEffect

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

有关 Compose 中动画的更多信息,请参阅 documentation