Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack

How to fill row nested in lazycolumn. JetpacCompose


I make my own and very simple calendar. Problem: I'm trying to display values ​​from a list. There are seven values ​​in one line. Each new line continues the list. Below is an example of invalid code. But he shows the essence and the problem)

          //.....
          LazyColumn (
            modifier = Modifier,
            content = {
                items(7) { row ->
                    Row {
                        for(n in 0..6){Text("${weeks1[n]}")}
                    }
                }
            }
        )

output:here

So i need to display list items like:

  • 1 2 3 4 5 6 7
  • 8 9 10 11 12 13 14
  • 15 16 17 18 19 20 21 etc.

Solution

  • I don't know if this is what you want but you can try this :

    val dates = MutableList(31) { it }
    
    LazyVerticalGrid(
        modifier = Modifier
            .fillMaxWidth()
            .systemBarsPadding(),
        columns = GridCells.Fixed(7),
        contentPadding = PaddingValues(horizontal = 16.dp, vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        items(dates) {
            Box(contentAlignment = Alignment.Center) {
                Text(text = "${it + 1}")
            }
        }
    }
    

    The result is :

    Result dates

    Update with alternative solution

    A solution with LazyColumn and Row with the same result (more difficult to achieve, less elegant)

    val dates = MutableList(35) { if (it + 1 > 31) -1 else it + 1 }
    val chunks = dates.chunked(7)
    
    LazyColumn(
        Modifier
            .fillMaxSize()
            .systemBarsPadding()
    ) {
        items(chunks) {
            Row(
                Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                it.forEach { date ->
                    Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) {
                        if (date != -1) Text(text = "$date")
                    }
                }
            }
        }
    }