Is there a way to measure a composable height with...
# compose-android
t
Is there a way to measure a composable height without laying it out? At the moment I’m doing it by adding the composable with a
alpha(0f)
and using the
onGloballyPositioned
to get the size. But I’m not sure this is the best option
m
I think setting an
alpha
to
0f
still makes it interactable/visible for a11y services which is probably not what you want here. You can simulate exactly what you say using a custom layout (by measuring the composable but not actually placing it) Take some inspiration from this thread: https://kotlinlang.slack.com/archives/C04TPPEQKEJ/p1723131281969339?thread_ts=1723127528.109779&cid=C04TPPEQKEJ
🦜 1
s
Also if you're interested just in its height, use onPlaced instead of onGloballyPositioned. It should be cheaper from what I understand
☝️ 1
t
Maybe I missed something but from the thread I couldn’t really use the modifier and make it work. I’ve changed to use
onPlaced
as suggested by Stylianos and solved it like this so far. I’m open to suggestions to improve it 😅
Copy code
@Composable
fun MeasureBox(
    content: @Composable () -> Unit,
    onMeasured: (IntSize) -> Unit,
) {
    var isMeasured by remember { mutableStateOf(false) }
    if (isMeasured) return
    Box(
        modifier = Modifier
            .alpha(0f)
            .onPlaced {
                isMeasured = true
                onMeasured(it.size)
            },
        content = { content() },
    )
}
s
if you just replace the alpha with the
withoutPlacement
does it not just work? And try by having the
onPlaced
modifier before/after to see if that makes any difference. Btw all of this measuring and the returning without rendering makes me feel like something fishy is going on 😄 Are you sure this is the only approach you got to solve what you're solving?
t
Idk if it’s, I need to measures of two composables, one compact and one expanded to control the maximum height some custom sheet can be dragged 😅
Using it like this also worked:
Copy code
modifier = Modifier
    .onPlaced {
        isMeasured = true
        onMeasured(it.size)
    }
    .withoutPlacement(),
🌟 1
295 Views