I’m developing a screen in Jetpack Compose that combines two scrolling components: a PullToRefresh for vertical scrolling and an ImageSlider implemented using HorizontalPager for horizontal scrolling. The PullToRefresh is going to allow users to refresh the screen content by pulling down.
However, I’m encountering an issue where the vertical scroll gesture for the PullToRefresh is not being detected. As a result, I’m unable to trigger the refresh operation by pulling down on the screen. The horizontal scrolling in the ImageSlider works as expected, but it seems to be interfering with the vertical scroll detection.
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PullToRefreshContent(
isRefreshing: Boolean,
onRefresh: () -> Unit,
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
val pullToRefreshState = rememberPullToRefreshState()
Box(modifier = modifier.nestedScroll(nestedScrollConnection)) {
content()
// Refresh logic
LaunchedEffect(isRefreshing) {
if (isRefreshing) pullToRefreshState.startRefresh()
else pullToRefreshState.endRefresh()
}
// PullToRefresh UI
PullToRefreshContainer(
state = pullToRefreshState,
modifier = Modifier.align(Alignment.TopCenter)
)
}
}
@Composable
fun ImageSlider(images: List<Media?>) {
val pagerState = rememberPagerState(initialPage = 0) { images.size }
HorizontalPager(state = pagerState) { currentPage ->
val painter = rememberAsyncImagePainter(model = images[currentPage]?.posterPath)
Card {
Image(painter = painter, contentDescription = null)
}
}
}
To resolve this conflict, I tried to implement a custom NestedScrollConnection to detect the scroll direction by examining the y offset of the scroll event. I assumed that a positive y offset would indicate a downward scroll.
However, this solution was not working. When monitoring the scroll events, I observed that the y offset value is consistently either 0.0 or -0.0, regardless of the actual scroll direction.
val nestedScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
//Vertical scroll
return if (available.y > 0) {
//Do refresh operation
onRefresh()
pullToRefreshState.nestedScrollConnection.onPreScroll(available, source)
}
//Horizontal scroll
else {
Offset.Zero
}
}
}
}
Azin Alizadeh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.