Created
May 30, 2021 08:33
-
-
Save zskamljic/98adebf71c5e4bb811b5f6d038dd3c8b to your computer and use it in GitHub Desktop.
This file contains 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
// ... 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