Last active
April 24, 2024 13:40
-
-
Save tasjapr/bb8591f34bdf2f6eea9dd20707a66c00 to your computer and use it in GitHub Desktop.
Accompanist pager with coil preloading and indicator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BoxWithConstraints { | |
val boxWithConstraintsScope = this | |
val height = (boxWithConstraintsScope.maxWidth - AppTheme.dimensions.padding_16 * 2) / 16 * 9 // Banner width to height ratio should be 16:9 | |
val context = LocalContext.current | |
val density = LocalDensity.current | |
ConstraintLayout { | |
val (pager, indicator) = createRefs() | |
val pagerState = rememberPagerState() | |
HorizontalPager( | |
count = banners.size, | |
state = pagerState, | |
modifier = Modifier | |
.height(height) | |
.fillMaxWidth() | |
.padding(top = AppTheme.dimensions.padding_20, start = AppTheme.dimensions.padding_16, end = AppTheme.dimensions.padding_16) | |
.background(AppTheme.colors.placeholderBackground, shape = AppShapes.medium) | |
.constrainAs(pager) { | |
top.linkTo(parent.top) | |
linkTo(start = parent.start, end = parent.end) | |
} | |
.clip(AppShapes.medium) | |
) { page -> | |
val request: ImageRequest | |
with(density) { | |
request = ImageRequest.Builder(context) | |
.data(banners[page].bannerUrl) | |
.size(width = boxWithConstraintsScope.maxWidth.roundToPx(), height = height.roundToPx()) | |
.crossfade(true) | |
.build() | |
context.imageLoader.enqueue(request) | |
} | |
AsyncImage( | |
model = request, | |
contentDescription = null, | |
contentScale = ContentScale.Crop, | |
modifier = Modifier.fillMaxSize() | |
) | |
} | |
if (banners.isNotEmpty()) Text( | |
text = "${pagerState.currentPage + 1}/${pagerState.pageCount}", | |
style = AppTheme.typography.body3, | |
color = AppTheme.colors.textPrimary, | |
modifier = Modifier | |
.background(color = AppTheme.colors.border, shape = AppShapes.small) | |
.animateContentSize() | |
.padding(vertical = AppTheme.dimensions.padding_3, horizontal = AppTheme.dimensions.padding_12) | |
.constrainAs(indicator) { | |
bottom.linkTo(pager.bottom, margin = 16.dp) | |
end.linkTo(parent.end, margin = 32.dp) | |
} | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result:
Screenrecorder-2022-12-14-15-31-20-42.0._2.mp4