Action on swipe to left. Jetpack Compose, Android

55 Views Asked by At

I'm new to Android Development and working right now on my first "real project" (just trying to copy iPhone calculator). The question is how do I implement deletion on swipe to left side of a screen exactly as on iPhone?

Here I've tried already something, but the problem is that yeah the code works, but on one swipe it can delete multiple numbers and not just one. How do I fix it?

Box(
    contentAlignment = Alignment.BottomEnd,
    modifier = Modifier
        .fillMaxWidth()
        .height(340.dp)
        .pointerInput(Unit) {
            detectHorizontalDragGestures { change, dragAmount ->
                val x = dragAmount
                if (x < 0 && currentValue != "0" && !currentValue.contains("-") && currentValueOnlyWithNumbers.length == 1) {
                    currentValue = "0"
                } else if (x < 0 && currentValue.contains("-") && currentValueOnlyWithNumbers.length == 1) {
                    currentValue = "0"
                } else if (x < 0 && currentValueOnlyWithNumbers.length > 1) {
                    currentValue =
                        if (currentValue.contains(" ") && currentValue[currentValue.length - 2] == ' ') {
                            currentValue.dropLast(2)
                        } else {
                            currentValue.dropLast(1)
                        }
                }
            }
        }
)
1

There are 1 best solutions below

0
Jan Itor On

detectHorizontalDragGestures has onDragStart and onDragEnd params which you can use to detect a single gesture. Update the total offset on each drag event and check if the gesture was a swipe left in onDragEnd. Optionally you can also remember the time when drag started to decide if the gesture was quick enough to be considered a swipe.

In this example I used an arbitrary value of -300 as a swipe detection threshold.

var offset by remember { mutableFloatStateOf(0f) }

Box(
    contentAlignment = Alignment.BottomEnd,
    modifier = Modifier
        .fillMaxWidth()
        .height(340.dp)
        .background(Color.LightGray)
        .pointerInput(Unit) {
            detectHorizontalDragGestures(
                onDragStart = { offset = 0f },
                onDragEnd = {
                    if (offset < -300) {
                        // Swipe left detected, implement deletion here
                    }
                }
            ) { _, dragAmount ->
                offset += dragAmount
            }
        }
)