Improve BottomSheet drag handling logic

This commit is contained in:
vfsfitvnm
2022-08-16 12:23:44 +02:00
parent 2a27701b18
commit 9e2768968b

View File

@@ -39,7 +39,6 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.Velocity
import androidx.compose.ui.unit.dp
import kotlin.math.absoluteValue import kotlin.math.absoluteValue
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
@@ -62,35 +61,29 @@ fun BottomSheet(
IntOffset(x = 0, y = y) IntOffset(x = 0, y = y)
} }
.pointerInput(state) { .pointerInput(state) {
var initialValue = 0.dp
val velocityTracker = VelocityTracker() val velocityTracker = VelocityTracker()
detectVerticalDragGestures( detectVerticalDragGestures(
onDragStart = {
initialValue = state.value
},
onVerticalDrag = { change, dragAmount -> onVerticalDrag = { change, dragAmount ->
velocityTracker.addPointerInputChange(change) velocityTracker.addPointerInputChange(change)
state.dispatchRawDelta(dragAmount) state.dispatchRawDelta(dragAmount)
}, },
onDragCancel = { onDragCancel = {
velocityTracker.resetTracking() velocityTracker.resetTracking()
state.snapTo(initialValue) state.snapTo(state.collapsedBound)
}, },
onDragEnd = { onDragEnd = {
val velocity = velocityTracker.calculateVelocity().y val velocity = -velocityTracker.calculateVelocity().y
velocityTracker.resetTracking() velocityTracker.resetTracking()
if (velocity.absoluteValue > 250 && initialValue != state.value) { if (velocity > 250) {
when (initialValue) { state.expand()
state.expandedBound -> state.collapse() } else if (velocity < -250) {
state.collapsedBound -> if (initialValue > state.value && onDismiss != null) { if (state.value < state.collapsedBound && onDismiss != null) {
state.dismiss() state.dismiss()
onDismiss.invoke() onDismiss.invoke()
} else { } else {
state.expand() state.collapse()
}
else -> state.expand()
} }
} else { } else {
val l0 = state.dismissedBound val l0 = state.dismissedBound
@@ -109,12 +102,9 @@ fun BottomSheet(
} }
in l1..l2 -> state.collapse() in l1..l2 -> state.collapse()
in l2..l3 -> state.expand() in l2..l3 -> state.expand()
else -> { else -> Unit
}
} }
} }
} }
) )
} }