Compose 中的 Progress indicators

319 阅读2分钟

在 Jetpack Compose 中,ProgressIndicator 是一种用于表示操作进度的组件。主要有两种类型的进度指示器:CircularProgressIndicatorLinearProgressIndicator。它们可以分别用于表示圆形和线性的进度。

进度指示器类型

  1. CircularProgressIndicator:圆形进度指示器。
  2. LinearProgressIndicator:线性进度指示器。

CircularProgressIndicator

示例代码

不确定进度的圆形进度指示器
@Composable
fun IndeterminateCircularProgressIndicatorDemo() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        CircularProgressIndicator()
    }
}

在这个示例中,CircularProgressIndicator 会不断旋转,表示操作正在进行,但没有具体的完成百分比。

确定进度的圆形进度指示器
@Composable
fun DeterminateCircularProgressIndicatorDemo() {
    var progress by remember { mutableStateOf(0.1f) }

    LaunchedEffect(Unit) {
        while (progress < 1f) {
            progress += 0.01f
            delay(100)
        }
    }

    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        CircularProgressIndicator(progress = progress)
    }
}

在这个示例中,我们使用了一个可变的 progress 状态,并在 LaunchedEffect 中模拟进度的增加。CircularProgressIndicatorprogress 参数用于指定进度值(0.0 到 1.0 之间)。

LinearProgressIndicator

示例代码

不确定进度的线性进度指示器
@Composable
fun IndeterminateLinearProgressIndicatorDemo() {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        LinearProgressIndicator()
    }
}

在这个示例中,LinearProgressIndicator 会持续显示一个动画条,表示操作正在进行,但没有具体的完成百分比。

确定进度的线性进度指示器
@Composable
fun DeterminateLinearProgressIndicatorDemo() {
    var progress by remember { mutableStateOf(0.1f) }

    LaunchedEffect(Unit) {
        while (progress < 1f) {
            progress += 0.01f
            delay(100)
        }
    }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        LinearProgressIndicator(progress = progress)
    }
}

在这个示例中,同样使用了一个可变的 progress 状态,并在 LaunchedEffect 中模拟进度的增加。LinearProgressIndicatorprogress 参数用于指定进度值(0.0 到 1.0 之间)。

详细讲解

  1. 状态管理

    var progress by remember { mutableStateOf(0.1f) }
    

    使用 remembermutableStateOf 创建一个浮点类型的状态来管理进度值。

  2. LaunchedEffect

    LaunchedEffect(Unit) {
        while (progress < 1f) {
            progress += 0.01f
            delay(100)
        }
    }
    

    使用 LaunchedEffectdelay 模拟进度的增加。LaunchedEffect 会在组件首次加载时启动协程,并在协程内逐步增加 progress 值。

  3. Box 和 Column

    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    )
    

    使用 BoxColumn 布局来居中显示进度指示器。

  4. CircularProgressIndicator 和 LinearProgressIndicator

    CircularProgressIndicator(progress = progress)
    LinearProgressIndicator(progress = progress)
    

    使用 CircularProgressIndicatorLinearProgressIndicator 显示圆形和线性的进度指示器,并通过 progress 参数设置当前进度值。

通过这些示例,你可以看到在 Jetpack Compose 中使用进度指示器是非常直观和灵活的。无论是表示不确定的进度,还是表示具体的完成百分比,都可以轻松实现。