Stefan Oltmann
05/16/2024, 5:29 PMStefan Oltmann
05/16/2024, 5:29 PMimport androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.offset
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.unit.IntOffset
import kotlin.math.roundToInt
@Composable
fun SwipeCard(
enabled: Boolean = true,
onSwipe: (SwipeDirection) -> Unit = {},
onSwipeEnded: (SwipeDirection) -> Unit = {},
swipeThreshold: Float = 300f,
sensitivityFactor: Float = 3f,
content: @Composable () -> Unit
) {
val offset = remember { mutableStateOf(0f) }
val lastDirection = remember { mutableStateOf(SwipeDirection.NONE) }
Box(
modifier = Modifier
.offset { IntOffset(offset.value.roundToInt(), 0) }
.pointerInput(enabled) {
if (!enabled)
return@pointerInput
detectHorizontalDragGestures(
onDragEnd = {
onSwipeEnded(lastDirection.value)
offset.value = 0f
},
onHorizontalDrag = { change, dragAmount ->
offset.value += (dragAmount / density) * sensitivityFactor
val direction = when {
offset.value > swipeThreshold ->
SwipeDirection.RIGHT
offset.value < -swipeThreshold ->
SwipeDirection.LEFT
else ->
SwipeDirection.NONE
}
if (lastDirection.value != direction)
onSwipe(direction)
lastDirection.value = direction
if (change.positionChange() != Offset.Zero)
change.consume()
}
)
}
.graphicsLayer(
rotationZ = animateFloatAsState(offset.value / 50).value
)
) {
content()
}
}
enum class SwipeDirection {
NONE,
LEFT,
RIGHT
}
Ankit Kumar
05/16/2024, 8:28 PMStefan Oltmann
05/16/2024, 11:04 PMStefan Oltmann
05/16/2024, 11:09 PMpointerInput
, but never calls onHorizontalDrag
Stefan Oltmann
05/16/2024, 11:13 PMdetectDragGestures
That's no problem for Compose for Desktop, but Android does not like it apparently 🤔Ankit Kumar
05/16/2024, 11:36 PMAnkit Kumar
05/16/2024, 11:37 PMStefan Oltmann
05/17/2024, 8:01 AMStefan Oltmann
05/17/2024, 8:01 AM