I’m attempting to make a layout such that it is a ...
# compose
j
I’m attempting to make a layout such that it is a row if the enclosed children will fit in the horizontal space given to the composable. If not, I wanted to swap to a column where each child is assigned a minWidth of the constrained horizontal space. I was able to get this working with a
SubcomposeLayout
by: 1. Call
subcompose
with the passed in width constraints 2. If the resulting placeables are too wide, call
subcompose
with constraints that has a minWidth of what was passed to the SubcomposeLayout. 3. I then only place either the horizontal or vertical placeables. The one problem I’m having with this approach is the semantics tree still knows about the horizontal subcomposition even though I never placed them. Is there a way to remove them or perhaps another way to approach this problem?
a
Use the
Layout
composable and avoid subcomposition for this. Use intrinsic sizes to determine whether things fit and then perform final measurement once you've decided the orientation
j
Thanks! Is there a good link on instric sizes?
a
start from the api docs, you can ask a
Measurable
for its minimum intrinsic width given a certain available height, for example
j
Awesome. https://developer.android.com/jetpack/compose/layouts/intrinsic-measurements this seems to be the resource to start with!
a
hmm, the custom layout snippet there looks wrong but the basic idea is there. It'll involve a call to the
Layout
composable rather than returning an object directly like that
o
You can check how
minIntrinsicWidth()
is used in this sample: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1648551227037639?thread_ts=1648467352.438719&cid=CJLTWPH7S As for me it would be useful to mention this approach in docs you linked.
j
Copy code
Layout(modifier = modifier, content = content) { measurables, constraints ->
        val totalWidth = measurables.sumOf {
            it.minIntrinsicWidth(constraints.maxHeight)
        }

        if (totalWidth > constraints.maxWidth) {
            columnLayout(measurables, constraints)
        } else {
            rowLayout(measurables, constraints)
        }
    }
I ended up doing this which seems to work! Thanks!
👍 2