Stephen Vinouze
11/15/2023, 11:38 AMonGloballyPositioned
and remembering this value that I then pass to an onClick callback. But this leads to unnecessary computation while the composable moves (normal given how the modifier works). With the view system, we could obtain such position at any time with getLocationOnScreen()
. Any idea? 🙂Zach Klippenstein (he/him) [MOD]
11/15/2023, 2:11 PMonGloballyPositioned
and onPlaced
give you the same LayoutCoordinates
instance every time they call you. That object will be valid as long as the node it refers to stays attached, and will always reflect the latest layout data.
Their difference is when they call you. onPlaced
calls you as soon as the parent places the component, and only subsequently when that local placement changes, so it’s much cheaper.
So you can use onPlaced
to get the LayoutCoordinates
instance, then just query it whenever you want.Stephen Vinouze
11/15/2023, 4:19 PMonGloballyPositioned
will do.Zach Klippenstein (he/him) [MOD]
11/15/2023, 5:37 PMLayoutCoordinates
to get position informationvar coords: LayoutCoordinates? by remember { mutableStateOf(null) }
Button(
onClick = { coords.positionInRoot },
modifier = Modifier.onPlaced { coords = it }
) { … }
If you don’t care about the event of the location changing, and only want to ask for the location at a future time, this is fine and more efficient than onGloballyPositioned
.Stephen Vinouze
11/15/2023, 5:40 PM