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