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

mgrazianodecastro

01/19/2023, 5:52 PM
Any better way of limiting the number of elements displayed in a
N
-sized list to
n
in a Lazy column? The only solution I could think for it, it is to place the items in a box container to fill
1/n
the parent height, so the user would scroll
n
elements at the screen.
l

Landry Norris

01/19/2023, 6:30 PM
You could create your own LimitedLazyColumn(n: Int, items: List<T>, …) and pass items.subList(0, n) (bonus points for checking if n < items.size), then call that when you need a limit.
m

mgrazianodecastro

01/19/2023, 6:32 PM
I would build that on top of LazyLayout? 👀
l

Landry Norris

01/19/2023, 6:35 PM
Copy code
@Composable
fun <T> LimitedLazyColumn(
    n: Int, items: List<T>, content: @Composable LazyItemScope.(Int) -> Unit
) {
    LazyColumn {
        items(items.subList(0, n.coerceAtMost(items.size)), content)
    }
}
This will create a LazyColumn with at most n items.
m

mgrazianodecastro

01/19/2023, 6:37 PM
hmmm, did you mean a lazy column which will have at most
n
items? If so, that's not the goal
l

Landry Norris

01/19/2023, 6:37 PM
I see now. You wanted to have all N items, but have n items fill the viewport.
How should this scale with screen size? Is n always the same, so I see huge boxes on a 14 inch chromebook and tiny boxes on a small phone?
m

mgrazianodecastro

01/19/2023, 6:40 PM
for now, I'm targeting only mobile. I can see how this can become complicated with other screens
That solution I made do work, but sometimes I try to look for more idiomatic ways of doing so
s

Saiedmomen

01/19/2023, 6:42 PM
do all elements have same height? How about measuring an element in a Layout and then drawing the LazyColumn with n time the element's height?
m

mgrazianodecastro

01/19/2023, 6:45 PM
no, the elements vary the size a little bit, but their total sum is always less than the parent height. Not only that, there's plenty of space between them, so they are kind of spread out
s

Saiedmomen

01/19/2023, 6:46 PM
Should the LazyColumn height change with current shown items then?
m

mgrazianodecastro

01/19/2023, 6:47 PM
the lazy column height is fixed. I'm trying to think about the solution you mentioned, but I don't have much experience with custom layouts
s

Saiedmomen

01/19/2023, 6:48 PM
Here is a fantastic introduction 👍

https://www.youtube.com/watch?v=zMKMwh9gZuI

m

mgrazianodecastro

01/19/2023, 6:49 PM
in terms of complexity, I'm willing to go with the one with less semantic overhead, and a simple box wrapper fills good, like so:
Copy code
LazyColumn(
    verticalArrangement = Arrangement.SpaceAround,
    ...
){
    items(...){
        Box(
            modifier = Modifier
            .fillParentMaxHeight(1/nf)
            ...
        ){...}
    }
}
but I'm gonna do the homework and study layout too lol. Thanks for the recommendation
5 Views