Android/Kotlin: cannot get the current swiped position in grid with onGloballyPositioned

5 days ago 7
ARTICLE AD BOX

I am trying to trigger functions while user is swiping on cells in a grid.

However, functions are triggered in random positions, even outside of the grid bounds.

What do I need to change to fix?

@Composable fun SwipeDetectGrid() { var childFrames by remember { mutableStateOf<Map<Int, Rect>>(emptyMap()) } var currentOverChild by remember { mutableStateOf<Int?>(null) } fun updateOverChild(globalOffset: Offset) { val overChild = childFrames.entries.firstOrNull { (_, rect) -> rect.contains(globalOffset) }?.key currentOverChild = overChild } Box( modifier = Modifier .fillMaxSize() .background(Color(0xFFEFEFEF)) .pointerInput(Unit) { detectDragGestures( onDragStart = { offset -> updateOverChild(offset) }, onDrag = { change, _ -> updateOverChild(change.position) }, onDragEnd = { currentOverChild = null }, onDragCancel = { currentOverChild = null } ) } ) { Column( modifier = Modifier .fillMaxHeight() .padding(16.dp) ) { for (row in 0..2) { Row( modifier = Modifier.fillMaxWidth() ) { for (col in 0..2) { val index = row * 3 + col Child( index, { i, rect -> childFrames = childFrames + (i to rect) }, modifier = Modifier .weight(1f) .aspectRatio(1f) ) } } } } currentOverChild?.let { id -> Text( text = "Over: Item $id", color = Color.White, modifier = Modifier .background(Color.Black) .padding(8.dp) .align(androidx.compose.ui.Alignment.TopCenter) ) } } } @Composable fun Child(i: Int, updateChildFrames: (Int, Rect) -> Unit, modifier: Modifier) { Box( modifier = modifier .background(Color.Cyan) .onGloballyPositioned { coordinates -> val rect = coordinates.boundsInRoot() updateChildFrames(i, rect) }, contentAlignment = Alignment.Center ) { Text( text = "Item $i", modifier = Modifier.padding(8.dp) ) } }
Read Entire Article