Is there maybe a way, to measure height of composa...
# compose
p
Is there maybe a way, to measure height of composable and react to it's current height? Like for example show text, that display the height
Text(text = heightPx.toString())
.
p
Layout {}
s
You could also user
onSizeChanged()
and
onGloballyPositioned{}
modifier extensions.
p
Hm, I think I want to use the height during the current frame (not previous). I guess
SubcomposeLayout
maybe?
p
Layout Composable gives you the constraints, you can also use BoxWithConstraint which internally uses SubcomposeLatout. The performance of Layout is way better over SubcomposeLatout. Unless you need to measure the children composable twice, Layout should do the job.
p
Let me know if I understand correctly. If I use
Layout
, I would need some sort of state for height.
var height by remember { MutableStateOf(0f)}
So when I measure the height of my element, I would update value of the height, which will in turn recompose and display height value to
Text
?
p
Not necessarily, you can have a scope to pass the constraints to your Composable, which will be a child of the Layout
p
do you mind showing/writing a simple a simple example of this?
You can actually be more generic and pass the @Composable content from the parent Composable.
The key here is defining a Scope interface to be able to communicate between layout and its children composables. The Scope between parent and children composables is a standard pattern in compose I guess
You can Google for more examples of Layout {}. The easy way would be using BoxWithConstraint but you will lose rendering speed
z
If you want to show it in the current frame, you have to use a SubcomposeLayout. But beware that is expensive and currently disables intrinsics.
2
👆 1
👆🏾 1
p
Yeah, notice Layout {} will pass twice
z
The one exception is that if you don’t need to be picky about the rendering of the size, you can draw the text yourself and do it in the same frame without subcomposition, but then you need to estimate the size required to draw that text without actually measuring it.
If you’re working on a debug tool or something, that might be good enough.
p
since
Layout
will pass twice, I was wondering if it might be same performant as
SubcomposeLayout
z
They each have their own performance characteristics. but before performance is correctness: the non-subcompose approach can only render the size a frame late. It may also cause infinite recomposition loops (e.g. if measuring the text rendering the size causes the thing being measured to re-measure). Performance-wise, the
Layout
approach may cause an extra frame than would otherwise be necessary, but it would only do it when the size changes.
SubcomposeLayout
has an ongoing cost for the bookkeeping required to manage a whole separate composition.
p
understood, thanks for answers guys
👍 1