https://kotlinlang.org logo
#compose
Title
# compose
p

PHondogo

10/23/2023, 8:31 AM
Hello! Is it possible to check if element is composed in scrollable content or not?
a

Alexander Zhirkevich

10/23/2023, 8:39 AM
Copy code
BoxWithConstraints {
      Text(if (constraints.hasBoundedHeight) "Static" else "Scrollable")
 }
mind blown 3
🙏 1
z

Zach Klippenstein (he/him) [MOD]

10/23/2023, 4:42 PM
Absolutely not
BoxWithConstraints
. If the element isn’t composed, that code won’t run at all, and if it is, it’s super inefficient. • If you’re in a lazy list, use LazyListLayoutInfo. • If not a lazy list, you can use a
DisposableEffect
to keep track of composed items is the simplest way (the effect will start when first composed, and be disposed when removed from composition). If you want to check if an item is visible, use the
LayoutCoordinates
of the item to get the clipped bounds. ◦ Depending on when you need to check visibility, you can use
onPlaced
(if you only need to check on demand) or
onGloballyPositioned
(if you need to check every time the visibility may have changed).
a

Alexander Zhirkevich

10/23/2023, 4:56 PM
I thought the question was not about if element is visible but about if parent is scrollable
p

PHondogo

10/23/2023, 5:00 PM
Yes. It is about how to check if parent is scrollable. BoxWithConstraint is normal solution (i dont check performance yet). But the better will be to use some Locals for that, cause with Box i need to wrap me element with it and pass root modifier to Box. But there is also need to apply modifier to my element.
a

Alexander Zhirkevich

10/23/2023, 5:07 PM
Yep, BoxWithConstraint isn't the most efficient thing, but having a lot of custom locals is not a good practice either
z

Zach Klippenstein (he/him) [MOD]

10/23/2023, 5:16 PM
Ah, ok. If you want to check constraints then it’s much cheaper to do it via a layout modifier:
Copy code
layout { measurable, constraints ->
  if (constraints.hasBoundedHeight) { … }
  val placeable = measurable.measure(constraints)
  layout(placeable.width, placeable.height) {
    placeable.placeRelative(0, 0)
  }
}
👍 2