snapFlingBehavior

Function

Common
fun snapFlingBehavior(
    snapLayoutInfoProvider: SnapLayoutInfoProvider,
    decayAnimationSpec: DecayAnimationSpec<Float>,
    snapAnimationSpec: AnimationSpec<Float>,
): TargetedFlingBehavior

A TargetedFlingBehavior that performs snapping to a given position in a layout.

You can use SnapLayoutInfoProvider.calculateApproachOffset to indicate that snapping should happen after this offset. If the velocity generated by the fling is high enough to get there, we'll use decayAnimationSpec to get to that offset and then we'll snap to the next bound calculated by SnapLayoutInfoProvider.calculateSnapOffset using snapAnimationSpec.

If the velocity is not high enough, we'll use snapAnimationSpec to approach and the same spec to snap into place.

Please refer to the sample to learn how to use this API.

Parameters

snapLayoutInfoProviderThe information about the layout being snapped.
decayAnimationSpecThe animation spec used to approach the target offset when the fling velocity is large enough. Large enough means large enough to naturally decay.
snapAnimationSpecThe animation spec used to finally snap to the correct bound.

Code Examples

SnapFlingBehaviorSimpleSample

@Composable
fun SnapFlingBehaviorSimpleSample() {
    val state = rememberLazyListState()
    LazyRow(
        modifier = Modifier.fillMaxSize(),
        verticalAlignment = Alignment.CenterVertically,
        state = state,
        flingBehavior = rememberSnapFlingBehavior(lazyListState = state),
    ) {
        items(200) {
            Box(
                modifier =
                    Modifier.height(400.dp).width(200.dp).padding(8.dp).background(Color.Gray),
                contentAlignment = Alignment.Center,
            ) {
                Text(it.toString(), fontSize = 32.sp)
            }
        }
    }
}

SnapFlingBehaviorCustomizedSample

@Composable
fun SnapFlingBehaviorCustomizedSample() {
    val state = rememberLazyListState()
    // If you'd like to customize either the snap behavior or the layout provider
    val snappingLayout = remember(state) { SnapLayoutInfoProvider(state) }
    val flingBehavior = rememberSnapFlingBehavior(snappingLayout)
    LazyRow(
        modifier = Modifier.fillMaxSize(),
        verticalAlignment = Alignment.CenterVertically,
        state = state,
        flingBehavior = flingBehavior,
    ) {
        items(200) {
            Box(
                modifier =
                    Modifier.height(400.dp).width(200.dp).padding(8.dp).background(Color.Gray),
                contentAlignment = Alignment.Center,
            ) {
                Text(it.toString(), fontSize = 32.sp)
            }
        }
    }
}