You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose中LinearProgressIndicator用animateFloatAsState无动画如何解决?

LinearProgressIndicator使用animateFloatAsState无动画的解决方案

问题原因

  • animateFloatAsState的动画触发前提是targetValue发生变化,你当前代码直接将targetValue写死为固定值0.35f,组件初始化时初始值和目标值完全一致,没有数值变化过程,因此不会触发过渡动画,直接显示最终进度。
  • 你需要的「每次组件出现在屏幕上都播放动画」的需求,本质是要在组件可见时主动触发一次从0到目标进度的数值变化。

修复代码

@Composable
fun MyIndicator(targetProgress: Float = 0.35f) {
    val progressAnimDuration = 1500
    // 存储动画目标值,初始为0
    var currentTarget by remember { mutableFloatStateOf(0f) }
    val progressAnimation by animateFloatAsState(
        targetValue = currentTarget,
        animationSpec = tween(durationMillis = progressAnimDuration, easing = FastOutSlowInEasing),
        label = "linear_progress_animation"
    )

    // 组件加载完成/目标进度变更时,修改目标值触发动画
    LaunchedEffect(targetProgress) {
        currentTarget = targetProgress
    }

    LinearProgressIndicator(
        progress = progressAnimation,
        modifier = Modifier           
           .fillMaxWidth()
           .clip(RoundedCornerShape(20.dp))
    )
}

进阶适配(每次可见都重新播放动画)

如果需要组件每次从不可见切回可见状态时都重新播放进度动画,可以配合生命周期监听,每次收到Lifecycle.Event.ON_RESUME事件时,先将currentTarget重置为0,再赋值为目标进度即可。

内容的提问来源于stack exchange,提问作者Johan Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 02:00:02