Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@saqib-github-commits
Last active April 11, 2023 10:02
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 saqib-github-commits/f0bbdbe592c6c07ec1ca6cd32b91a324 to your computer and use it in GitHub Desktop.
Save saqib-github-commits/f0bbdbe592c6c07ec1ca6cd32b91a324 to your computer and use it in GitHub Desktop.
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun HorizontalPagerWithNextPrevButtonExample() {
val pagerState = rememberPagerState()
val coroutineScope = rememberCoroutineScope()
Box (
modifier = Modifier
.fillMaxWidth()
.height(300.dp)
) {
HorizontalPager(pageCount = 5, state = pagerState) { pageIndex ->
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Gray),
contentAlignment = Alignment.Center
) {
Text(text = "Current Page Index $pageIndex")
}
}
Row(modifier = Modifier
.align(Alignment.BottomCenter)
.padding(bottom = 16.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
val prevButtonVisible = remember {
derivedStateOf {
pagerState.currentPage > 0
}
}
val nextButtonVisible = remember {
derivedStateOf {
pagerState.currentPage < 4 // total pages are 5
}
}
Button(
enabled = prevButtonVisible.value,
onClick = {
val prevPageIndex = pagerState.currentPage - 1
coroutineScope.launch { pagerState.animateScrollToPage(prevPageIndex) }
},
) {
Text(text = "Prev")
}
Button(
enabled = nextButtonVisible.value ,
onClick = {
val nextPageIndex = pagerState.currentPage + 1
coroutineScope.launch { pagerState.animateScrollToPage(nextPageIndex) }
},
) {
Text(text = "Next")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment