Hi there! Probably won’t get a different solution ...
# compose
s
Hi there! Probably won’t get a different solution but here goes nothing 😄 I was wondering if we can somehow get the composable’s position on screen at runtime? I’m currently getting the position with
onGloballyPositioned
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? 🙂
z
Both
onGloballyPositioned
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.
s
Thxs for the clarification. What do you mean exactly by querying it? In my case, the component can change its position on the screen (like scrolling). But the querying matters as I’d ideally like to get those exact coordinates when clicking on a button for instance. But it seems only going through the computation with
onGloballyPositioned
will do.
z
By querying i mean calling methods on
LayoutCoordinates
to get position information
e.g.
Copy code
var 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
.
s
True, I don't see why I should do the computation up front. Storing directly the layout coordinates from the onplaced then doing the final computation when wanted. Thxs for the hint!
👍🏻 1