I have tried to use this answer where he uses OnGloballyPositionedModifier
but it is not returning the correct absolute Pos of my children.I tried positionInWindow()
, positionInRoot()
. It appears to work when the column
does the spacing but not when I do it with offset
.
@Composable
fun GetAbsolutePos(
content: @Composable () -> Unit,
) {
Box(modifier = Modifier
.onGloballyPositioned { coordinates ->
println("My coordinates: " + coordinates.positionInRoot())
}
) {
content()
}
}
@Preview
@Composable
fun test() {
GetAbsolutePos() {
Box(
modifier = Modifier
.width(PixelToDp(pixelSize = 200))
.offset(x = PixelToDp(pixelSize = 100), y = PixelToDp(pixelSize = 50))
.height(PixelToDp(pixelSize = 200))
.background(Color.Red)
) {
GetAbsolutePos() {
Column(
) {
GetAbsolutePos() {
Box(
Modifier
.size(PixelToDp(pixelSize = 20))
.background(Color.Green)
)
}
GetAbsolutePos() {
Box(
Modifier
.size(PixelToDp(pixelSize = 20))
.background(Color.Blue)
)
}
}
}
}
}
}
which prints the following
I/System.out: My coordinates: Offset(0.0, 0.0) // wrong I used offset, it should be 100x50
I/System.out: My coordinates: Offset(100.0, 50.0) // correct
I/System.out: My coordinates: Offset(100.0, 50.0) // correct
I/System.out: My coordinates: Offset(100.0, 70.0) // correct? so it works on column spacing but not with offset????
Is there a way to get the Absolute Position of my composable function in relation to the whole ANDROID WINDOW?
Edit1:
@Composable
fun PixelToDp(pixelSize: Int): Dp {
return with(LocalDensity.current) { pixelSize.toDp() }
}
EDIT:2
The order of modifier should not matter since the function onGloballyPositioned
states that.
This callback will be invoked at least once when the LayoutCoordinates are available, and every time the element's position changes within the window.
The same is true for onSizeChanged
and can be observed by running the code below (same example as in the answer by @Thracian.)
Invoked with the size of the modified Compose UI element when the element is first measured or when the size of the element changes.
Since the function is literally a callback the order shouldn't matter. If im wrong with this pls feel free to correct me.
Box(modifier = Modifier
.onSizeChanged {
println(" Size 1: $it")
}
.size(PixelToDp(pixelSize = 150))
.onSizeChanged {
println(" Size 2: $it")
}
.background(Color.Red)
)
Prints
I/System.out: Size 2: 150 x 150
I/System.out: Size 1: 150 x 150