Skip to content

Instantly share code, notes, and snippets.

@zskamljic
Created May 30, 2021 08:33
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 zskamljic/98adebf71c5e4bb811b5f6d038dd3c8b to your computer and use it in GitHub Desktop.
Save zskamljic/98adebf71c5e4bb811b5f6d038dd3c8b to your computer and use it in GitHub Desktop.
// ... other remembered values
// Required to call animateScrollTo
val scope = rememberCoroutineScope()
// A place to store item positions
val indices = remember { IntArray(itemCount) { 0 } }
val flingBehavior = object : FlingBehavior {
override suspend fun ScrollScope.performFling(initialVelocity: Float): Float {
// Get the current scroll position
val value = scrollState.value
// Find the closest item based on position
indices.minByOrNull { abs(it - value) }?.let {
scope.launch {
scrollState.animateScrollTo(it)
}
}
return initialVelocity
}
}
Box(modifier = Modifier.onSizeChanged { size = it }) {
Layout(
// We use our flingBehavior here
modifier = Modifier.verticalScroll(scrollState, flingBehavior = flingBehavior),
content = { repeat(itemCount) { item(it) } }
) { measurables, constraints ->
// Creating the placeables ...
layout(constraints.maxWidth, size.height + contentHeight) {
// ...
placeables.forEachIndexed { index, placeable ->
// Placing the item ...
// Store the vertical center of the item, yPosition holds the position including the top margin
indices[index] = yPosition - startOffset
yPosition += placeable.height + itemSpacing
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment