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

dimsuz

04/21/2022, 12:31 PM
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

Filip Wiesner

04/21/2022, 12:34 PM
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

dimsuz

04/21/2022, 12:37 PM
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

Filip Wiesner

04/21/2022, 12:39 PM
I just saw
weight
working in scrollable
Column
so I thought this would work
d

dimsuz

04/21/2022, 2:15 PM
Hmm, I'll recheck.
z

Zach Klippenstein (he/him) [MOD]

04/21/2022, 5:21 PM
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

Filip Wiesner

04/21/2022, 5:59 PM
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

dimsuz

04/22/2022, 10:27 AM
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

Zach Klippenstein (he/him) [MOD]

04/22/2022, 4:11 PM
Doing everything in a single layout pass is a lot more elegant than using subcomposition at least.
5 Views