如何在 Jetpack Compose 中为 LinearProgressIndicator 的进度设置动画?

Joh*_*aul 14 android android-jetpack-compose

我有一个LinearProgressIndicator可以正确显示当前进度的。现在我希望进度是动画的,我认为这会非常简单animateFloatAsState。好吧,不确定我没有理解什么,但是使用下面的代码,进度不是动画的,而是立即显示在正确的位置。

@Composable
fun MyIndicator() {
    val progressAnimDuration = 1500
    val progressAnimation by animateFloatAsState(
        targetValue = 0.35f
        animationSpec = tween(durationMillis = progressAnimDuration, easing = FastOutSlowInEasing)
    )
     LinearProgressIndicator(
        progress = progressAnimation,
        ...
        modifier = Modifier           
           .fillMaxWidth()
           .clip(RoundedCornerShape(20.dp)). // Rounded edges
    )
}
Run Code Online (Sandbox Code Playgroud)

因此,每当我在屏幕上显示该组件时,我都希望进度能够动画化到正确的进度状态。但相反,进度不是动画的,而是立即以正确的进度状态显示。

这是怎么回事?:)

Dan*_*uks 21

我遇到了类似的问题,在我的例子中,我使用 LaunchedEffect 将进度从零更新到所需值

@Composable
fun MyIndicator(indicatorProgress: Float) {
   var progress by remember { mutableStateOf(0f) }
    val progressAnimDuration = 1500
    val progressAnimation by animateFloatAsState(
        targetValue = indicatorProgress, 
        animationSpec = tween(durationMillis = progressAnimDuration, easing = FastOutSlowInEasing)
    )
    LinearProgressIndicator(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(20.dp)), // Rounded edges
        progress = progressAnimation
    )
    LaunchedEffect(indicatorProgress) {
        progress = indicatorProgress
    }
}
Run Code Online (Sandbox Code Playgroud)