theapache64
12/29/2021, 8:00 PMLayoutCoordinates
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 : $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 ?
😒tackoverflow: SO Thread: https://stackoverflow.com/questions/70524414/jetpack-compose-how-do-i-know-if-a-composable-is-fully-visible