Jetpack Compose : How do I know if a composable is fully visible?

Viewed 607

Currently am using Modifier#onGloballyPositioned's LayoutCoordinates to find if the composable is in the viewport.

val configuration = LocalConfiguration.current
Modifier.onGloballyPositioned { layoutCoordinates ->
    val (width, height) = layoutCoordinates.size
    val (x1, y1) = layoutCoordinates.positionInRoot()
    val x2 = x1 + width
    val y2 = y1 + height
    val screenWidth = configuration.screenWidthDp.toPx
    val screenHeight = configuration.screenHeightDp.toPx
    val isFullyVisible = (x1 >= 0 && y1 >= 0) && (x2 <= screenWidth && y2 <= screenHeight)
    println("isFullyVisible : $id -> $isFullyVisible")
}

// To convert Dp to Px
val Number.toPx
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        this.toFloat(),
        Resources.getSystem().displayMetrics
    )

It works, but am wondering if there’s any better built-in API available to do this. If not, is there any optimisation that I need to do on the above approach?

0 Answers
Related