在 Jetpack Compose 中,ProgressIndicator 是一种用于表示操作进度的组件。主要有两种类型的进度指示器:CircularProgressIndicator 和 LinearProgressIndicator。它们可以分别用于表示圆形和线性的进度。
进度指示器类型
- CircularProgressIndicator:圆形进度指示器。
- 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 中模拟进度的增加。CircularProgressIndicator 的 progress 参数用于指定进度值(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 中模拟进度的增加。LinearProgressIndicator 的 progress 参数用于指定进度值(0.0 到 1.0 之间)。
详细讲解
-
状态管理:
var progress by remember { mutableStateOf(0.1f) }使用
remember和mutableStateOf创建一个浮点类型的状态来管理进度值。 -
LaunchedEffect:
LaunchedEffect(Unit) { while (progress < 1f) { progress += 0.01f delay(100) } }使用
LaunchedEffect和delay模拟进度的增加。LaunchedEffect会在组件首次加载时启动协程,并在协程内逐步增加progress值。 -
Box 和 Column:
Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center )使用
Box和Column布局来居中显示进度指示器。 -
CircularProgressIndicator 和 LinearProgressIndicator:
CircularProgressIndicator(progress = progress) LinearProgressIndicator(progress = progress)使用
CircularProgressIndicator和LinearProgressIndicator显示圆形和线性的进度指示器,并通过progress参数设置当前进度值。
通过这些示例,你可以看到在 Jetpack Compose 中使用进度指示器是非常直观和灵活的。无论是表示不确定的进度,还是表示具体的完成百分比,都可以轻松实现。