androidkotlinandroid-jetpack-composeandroid-jetpack

Jetpack Compose - get click position in custom layout


I am working on a custom layout that presents a day timeline in Jetpack Compose using Layout composable. The result looks like Google's Calenar and code is similar to the one described in that great tutorial: https://danielrampelt.com/blog/jetpack-compose-custom-schedule-layout-part-1/

My question is however: How could I receive (x, y) position of a click within a Layout composable. I could easily receive clicks made on children of the Layout by adding clickable modifier to the placeables. My question is however, how I receive position of clicks made on the space of layout between the childeren

(that would be the space between appointments in the day timeline according to previously mentioned example. And in that case I need the position of the click to get info on which hour user clicked)

I tried to add .clickable modifier on the whole Layout composable, but I do not receive (x, y) position of the click within the layout in the onClick lambda (it's type is () -> Unit)


Solution

  • You can use detectTapGestures, it'll return the offset:

    Modifier.pointerInput(Unit) {
        detectTapGestures { offset ->
    
        }
    }
    

    If you need to add a ripple effect to this gesture, see this answer. In your case, you may need an array of MutableInteractionSource for each child view and one for the parent view.

    You can find more custom gestures in Compose documentation.