我的应用程序需要一个 ProgressBar,我正在尝试使用 Jetpack Compose 来实现它,所以要么我需要一个内置的 ProgressBar 支持(我没有找到它),要么应该有一种机制来使用 Compose 显示普通的 Android Widget。这有可能吗?
问问题
12615 次
3 回答
38
当然,我们在 Jetpack Compose 中有进度条:
CircularProgressIndicator:将进度条显示为圆形。这是不确定的。以样式中的原色为主题。另一个变体是确定的,它在参数中取得进展为 Float (0.0f - 1.0f)
例子:
// Indeterminate
CircularProgressIndicator()
// Determinate
CircularProgressIndicator(progress = 0.5f)
LinearProgressIndicator:将进度条显示为线。这是不确定的。以样式中的原色为主题。另一个变体是确定的,它在参数中取得进展为 Float (0.0f - 1.0f)
例子:
// Indeterminate
LinearProgressIndicator()
// Determinate
LinearProgressIndicator(progress = 0.5f)
于 2020-01-21T07:29:00.240 回答
18
1.0.x
你可以使用LinearProgressIndicator
orCircularProgressIndicator
// Indeterminate
CircularProgressIndicator()
LinearProgressIndicator()
// Determinate
CircularProgressIndicator(progress = ..)
LinearProgressIndicator(progress = ..)
例子:
var progress by remember { mutableStateOf(0.1f) }
LinearProgressIndicator(
backgroundColor = Color.White,
progress = progress,
color = blue700
)
要更新值,您可以使用以下内容:
// { if (progress < 1f) progress += 0.1f }
于 2020-08-28T12:34:01.533 回答
1
对于圆角,我们可以使用此代码(它与 LinearProgress 相同,但有一个小修正 - 在 drawLine 我们使用参数 StrokeCap.Round 进行舍入)
@Composable
fun LinearRoundedProgressIndicator(
/*@FloatRange(from = 0.0, to = 1.0)*/
progress: Float,
modifier: Modifier = Modifier,
color: Color = MaterialTheme.colors.primary,
backgroundColor: Color = color.copy(alpha = ProgressIndicatorDefaults.IndicatorBackgroundOpacity)
) {
val linearIndicatorHeight = ProgressIndicatorDefaults.StrokeWidth
val linearIndicatorWidth = 240.dp
Canvas(
modifier
.progressSemantics(progress)
.size(linearIndicatorWidth, linearIndicatorHeight)
.focusable()
) {
val strokeWidth = size.height
drawRoundedLinearIndicatorBackground(backgroundColor, strokeWidth)
drawRoundedLinearIndicator(0f, progress, color, strokeWidth)
}
}
private fun DrawScope.drawRoundedLinearIndicatorBackground(
color: Color,
strokeWidth: Float
) = drawRoundedLinearIndicator(0f, 1f, color, strokeWidth)
private fun DrawScope.drawRoundedLinearIndicator(
startFraction: Float,
endFraction: Float,
color: Color,
strokeWidth: Float
) {
val width = size.width
val height = size.height
// Start drawing from the vertical center of the stroke
val yOffset = height / 2
val isLtr = layoutDirection == LayoutDirection.Ltr
val barStart = (if (isLtr) startFraction else 1f - endFraction) * width
val barEnd = (if (isLtr) endFraction else 1f - startFraction) * width
// Progress line
drawLine(color, Offset(barStart, yOffset), Offset(barEnd, yOffset), strokeWidth, StrokeCap.Round)
}
于 2021-09-02T12:09:05.127 回答