https://kotlinlang.org logo
#compose
Title
# compose
s

ste

07/25/2022, 5:34 PM
How can I add a good looking fling behaviour to the red rect? All I see is the velocity tracker returning nonsense values (most of the times) - what am I missing?
Copy code
val coroutineScope = rememberCoroutineScope()
val offsetX = remember { Animatable(0f) }

BoxWithConstraints(
    modifier = Modifier
        .fillMaxSize()
) {
    Box(
        modifier = Modifier
            .offset { IntOffset(offsetX.value.roundToInt(), 0) }
            .fillMaxHeight()
            .width(50.dp)
            .background(Color.Red)
            .pointerInput(Unit) {
                val velocityTracker = VelocityTracker()
                val decay = splineBasedDecay<Float>(this)

                offsetX.updateBounds(0f, constraints.maxWidth - 50.dp.toPx())

                detectHorizontalDragGestures(
                    onHorizontalDrag = { change, dragAmount ->
                        coroutineScope.launch { offsetX.snapTo(offsetX.value + dragAmount) }
                        velocityTracker.addPointerInputChange(change)
                    },
                    onDragEnd = {
                        val velocity = velocityTracker.calculateVelocity().x
                        velocityTracker.resetTracking()

                        val target = decay.calculateTargetValue(offsetX.value, velocity)

                        coroutineScope.launch {
                            offsetX.animateTo(target, initialVelocity = velocity)
                        }
                    }
                )
            }
    )
}
a

andrew

07/25/2022, 11:13 PM
You can steal the swipeable impl from material
s

ste

07/26/2022, 6:31 AM
I believe the problem is the velocity is not calculated correctly when
pointerInput
is targeted by
offset
. If I move the
pointerInput
to the upper composable, there are no issues - however this will make the rect draggable by anywhere, which is not what I want
14 Views