Skip to content

Instantly share code, notes, and snippets.

@svenjacobs
Created April 4, 2024 12:41
Show Gist options
  • Save svenjacobs/5b3b4e5c28a2cbfed2007d2e2b5651d0 to your computer and use it in GitHub Desktop.
Save svenjacobs/5b3b4e5c28a2cbfed2007d2e2b5651d0 to your computer and use it in GitHub Desktop.
Segmented progress bar in Jetpack Compose
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@Composable
fun SegmentedProgressBar(
segments: Int,
progress: Int,
modifier: Modifier = Modifier,
completedColor: Color = Color.Green,
incompleteColor: Color = Color.Gray,
height: Dp = 24.dp,
segmentCornerSize: Dp = 2.dp,
firstLastSegmentCornerSize: Dp = 12.dp,
spaceBetweenSegments: Dp = 4.dp,
) {
require(segments >= 2) { "segments must be equal to or greater than 2" }
require(progress in 0..segments) { "progress must be less than or equal to segments" }
Row(
modifier = modifier.height(height),
horizontalArrangement = Arrangement.spacedBy(spaceBetweenSegments),
) {
for (index in 0 until segments) {
val shape = when (index) {
0 -> RoundedCornerShape(
topStart = firstLastSegmentCornerSize,
topEnd = segmentCornerSize,
bottomStart = firstLastSegmentCornerSize,
bottomEnd = segmentCornerSize,
)
segments - 1 -> RoundedCornerShape(
topStart = segmentCornerSize,
topEnd = firstLastSegmentCornerSize,
bottomStart = segmentCornerSize,
bottomEnd = firstLastSegmentCornerSize,
)
else -> RoundedCornerShape(segmentCornerSize)
}
val color = if (index < progress) completedColor else incompleteColor
Box(
modifier = Modifier
.clip(shape)
.background(color)
.fillMaxHeight()
.weight(1f),
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment