Skip to content

进度条 (Progress)

源:Compose 进度指示器

M3 提供了线性 (LinearProgressIndicator) 和圆形 (CircularProgressIndicator) 两种指示器。每种都支持确定性(显示具体百分比)和不确定性(无限加载)两种状态。

1. 线性进度条 (Linear)

kotlin
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
    // 1. 不确定性 (无限加载)
    LinearProgressIndicator(
        modifier = Modifier.fillMaxWidth(),
        color = MaterialTheme.colorScheme.secondary,
        trackColor = MaterialTheme.colorScheme.surfaceVariant,
    )

    // 2. 确定性 (显示进度 0.0 ~ 1.0)
    LinearProgressIndicator(
        progress = { 0.7f }, // 进度 70%
        modifier = Modifier.fillMaxWidth(),
    )
}

2. 圆形进度条 (Circular)

kotlin
Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
    // 1. 不确定性
    CircularProgressIndicator()

    // 2. 确定性
    CircularProgressIndicator(
        progress = { 0.7f },
        modifier = Modifier.size(64.dp),
        color = Color.Green,
        strokeWidth = 8.dp // 调整粗细
    )
}

3. 自定义动画

默认的 progress 参数变化是没有动画的。如果需要平滑过渡,可以使用 animateFloatAsState

kotlin
var progress by remember { mutableFloatStateOf(0.1f) }
// 添加动画平滑过渡
val animatedProgress by animateFloatAsState(
    targetValue = progress,
    animationSpec = ProgressIndicatorDefaults.ProgressAnimationSpec
)

CircularProgressIndicator(progress = { animatedProgress })

// 模拟进度增加
Button(onClick = { if (progress < 1f) progress += 0.1f }) {
    Text("增加进度")
}