Skip to content

Instantly share code, notes, and snippets.

@shohiebsense
Last active February 21, 2022 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shohiebsense/54d8ca16fdfb1b41b343f19de6c1d49a to your computer and use it in GitHub Desktop.
Save shohiebsense/54d8ca16fdfb1b41b343f19de6c1d49a to your computer and use it in GitHub Desktop.
Animated Pager Indicator Jetpack Compoes
@ExperimentalAnimationApi
@ExperimentalPagerApi
@Composable
fun HorizontalPagerIndicator2(
pagerState: PagerState,
modifier: Modifier = Modifier,
activeColor: Color = LocalContentColor.current.copy(alpha = LocalContentAlpha.current),
inactiveColor: Color = activeColor.copy(ContentAlpha.disabled),
indicatorHeight: Dp = 8.dp,
spacing: Dp = 8.dp,
indicatorShape: Shape = RoundedCornerShape(4.dp),
) {
val indicatorWidthPx = LocalDensity.current.run { 8.dp.roundToPx() }
val spacingPx = LocalDensity.current.run { spacing.roundToPx() }
Box(
modifier = modifier,
contentAlignment = Alignment.CenterStart
) {
Row(
horizontalArrangement = Arrangement.spacedBy(spacing),
verticalAlignment = Alignment.CenterVertically,
) {
val indicatorModifier = Modifier
.size(width = 8.dp, height = indicatorHeight)
.background(color = inactiveColor, shape = indicatorShape)
repeat(pagerState.pageCount) {
Box(indicatorModifier)
}
}
val scrollPosition = (pagerState.currentPage + pagerState.currentPageOffset)
.coerceIn(
0f,
(pagerState.pageCount - 1)
.coerceAtLeast(0)
.toFloat()
)
val value by animateFloatAsState(
targetValue = if (scrollPosition % 1 == 0F) 8F else 16F,
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
)
Box(
Modifier
.offset {
IntOffset(
x = ((spacingPx + indicatorWidthPx) * scrollPosition).toInt(),
y = 0
)
}
.size(width = value.dp, height = indicatorHeight)
.background(
color = activeColor,
shape = indicatorShape,
)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment