Hello everyone, I have a question about calculatin...
# compose-android
s
Hello everyone, I have a question about calculating the absolute position of a composable on the screen. I’m trying to determine how many dp a specific composable is positioned from the bottom of the screen. I’ve attempted using
positionInWindow()
, but it didn’t quite meet my requirements. If anyone knows the correct approach or can provide guidance, I would greatly appreciate it! 😊
a
There’s
positionOnScreen()
, but I’d be suspicious of most cases of calculating things relative to the overall screen dimension versus calculating within your window
s
@Stylianos Gakis @Alex Vanyo Using the coordinates obtained from
positionInWindow()
and subtracting the screen size and navigation bar height, I was able to implement the solution successfully. It turned out that the issue was caused by not considering the navigation bar size earlier. Thank you for your response! Code:
Copy code
fun Modifier.calculateDistanceFromBottom(
    onDistanceCalculated: (Dp) -> Unit
): Modifier = composed {
    val density = LocalDensity.current
    val view = LocalView.current
    val context = LocalContext.current

    val windowHeightDp = with(density) { view.rootView.height.toDp() }
    val systemBottomPadding = context.getBottomNavigationBarHeight()

    var lastDistanceCache by remember { mutableStateOf<Dp?>(null) }

    this.onGloballyPositioned { layoutCoordinates ->
        val viewWindowPositionDp = with(density) { layoutCoordinates.positionInWindow().y.toDp() }
        val viewHeightDp = with(density) { layoutCoordinates.size.height.toDp() }
        val viewBottomPositionDp = viewWindowPositionDp + viewHeightDp
        val bottomDistanceDp = windowHeightDp - viewBottomPositionDp - systemBottomPadding

        if (lastDistanceCache != bottomDistanceDp) {
            lastDistanceCache = bottomDistanceDp
            onDistanceCalculated(bottomDistanceDp)
        }
    }
}
👍 1