How do I get the position of a click? When using `...
# compose
m
How do I get the position of a click? When using
Modifier.onClick
, you don't get the position, and when using
Modifier.onPointerEvent(PointerEventType.Release)
you do get a position, but that won't detect clicks correctly, as it will also fire for drags.
w
detectTapGestures
? You can manually wait for release if that's critical.
1
s
Also note that drags that end within the bounds are considered clicks as well, by both
clickable
and
detectTapGestures
(which is the correct behavior), and
detectTapGestures
will give you the offset when the cursor was released, not when it was first pressed.
m
Hmm,
detectTapGestures
works but now I can only detect left clicks. I am interested in both left clicks and right clicks (and need to know which is which). In
onPointerEvent
I could check the button.
s
Wrote this in a hurry, but I guess this should do?
Copy code
Modifier.pointerInput(Unit) {
    awaitPointerEventScope {
        while (true) {
            val event = awaitPointerEvent()
            if (event.type == PointerEventType.Release) {
                val position = event.changes.lastOrNull()?.position
                if (position != null && position in size.toIntRect().toRect()) {
                    val button = event.button
                    println("released at position $position using button $button!")
                }
            }
        }
    }
}
TL;DR: check event type, if it's
Release
, make sure that we're inside the bounds of the clickable (unsure if there's a better way, but I just check if the position is inside the
size
converted into a
Rect
).
I may be missing something, but I feel like Compose could (and should) provide more convenience APIs for this kind of thing.
m
But this will also trigger for drags, no? I don't want click events for when someone drags. I am displaying a UI like in Google Maps, you can drag the surface around, left click objects to select and right-click objects for a context menu. I don't want a drag to select something or open a context menu.
s
Ahh I see, in that case the code for dragging could be before this one? Because this will only get events that were not consumed yet, afaik
w
You can probably just copy out the implementation of
detectTapGestures
but have it intercept right click instead.