If I have a `Row` and if a sum width of all of its...
# compose
d
If I have a
Row
and if a sum width of all of its children is less than
screenWidth
I want to use
.weight(1)
for them. Otherwise I want to use
.horizontalScroll()
on the
Row
. Is there a nice way to achieve this? I thought about
SubcomposeLayout
instead of
Row
but I'm not sure, because I need to also manipulate
Modifier
in this case (for scrolling)
f
If you add weight to all children and put them in a scrolling container at the same time, wouldn't that achieve this behavior? 🤔 Not sure, just a thought
d
No, in this case they will be measured with Constraint.Infinite and this will result in "wrap content" measurement,
weight(1)
will have no effect.
f
I just saw
weight
working in scrollable
Column
so I thought this would work
d
Hmm, I'll recheck.
z
If that works I'll be surprised. It would have to measure the items once to find out if they can fit, and if they do, measure them again with the weight, which is 2 measurements which isn't allowed.
I think you could do something like this:
Copy code
var viewportSize by remember { mutableStateOf(Size.Unspecified) }

Layout(
  content = content,
  modifier = modifier
    .onSizeChanged { viewportSize = it }
    .verticalScroll(…)
) { m, c ->
  // Use intrinsics to determine if items will fit inside viewportSize. 
  // If they do, measure with equal fixed constraints. 
  // If not, measure with unbounded constraints.
  …
}
That should work as long as onSizeChanged is called before the verticalScroll measures its contents, which I'm not sure will happen. Actually I don't think it can. So you can replace onSizeChanged with a custom pass through layout modifier that stores the max constraints from before the verticalScroll in that state.
f
I was surprised too. I'll try to remember tomorrow to look at the place where I saw it.
Yeah, I didn't read the question properly, sorry. I thought you meant you want to have bunch of items with space between them using weight. And it would start scrolling when the size of the spaces would reach zero.
d
Thanks, Zach! That solution about storing in the state and doing this in 2 stages crossed my mind, but I thought maybe there's a more "elegant" solution.
z
Doing everything in a single layout pass is a lot more elegant than using subcomposition at least.