Search code examples
androidkotlinandroid-jetpack-compose

Make each item the same size


I've created a table from this code in my app. My problem is that when the text in one cell requires more than one line, only the one cell will resize instead of all cells in the row. This looks really ugly. I've already tried using Modifier.onSizeChanged to change the height of each other cell but it didn't work.

Image of table

Code:

data class Cell(
    val name: String,
    val weight: Float
)

@Composable
fun RowScope.TableCell(...) { /* same as in the linked code */ }

@Composable
fun MyTable(data: List<Something>) {
    val columns = listOf(
        Cell("a", .25f),
        Cell("b", .25f),
        Cell("c", .25f),
        Cell("d", .25f)
    )

    LazyColumn(
        Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        item {
            Row {
                columns.forEach {
                    TableCell(
                        text = it.name,
                        weight = it.weight
                    )
                }
            }
        }

        items(data) {
            Row(Modifier.fillMaxWidth()) {
                TableCell(
                    text = it.somenumber.toString(),
                    weight = columns[0].weight
                )

                TableCell(
                    text = "Abc",
                    weight = columns[1].weight
                )

                TableCell(
                    text = it.somestring1,
                    weight = columns[2].weight
                )

                TableCell(
                    text = it.somestring2,
                    weight = columns[3].weight
                )
            }
        }
    }
}

Solution

  • In such cases, you should use Modifier.height(IntrinsicSize.Min): it will override the height constraint which is set to infinity by scrollable LazyColumn. Then you can apply Modifier.fillMaxHeight to your TableCell.