Is there a ready-made way to make a table? That is...
# compose
t
Is there a ready-made way to make a table? That is, a grid with cells that are always vertically and horizontally aligned with each other. I'm reimplementing this game https://lab.brainonfire.net/sum1337/ as a learning project and I basically just need a way to make a square grid.
I've tried putting Boxes in Rows with
weight(1f)
, but the alignment sometimes "wanders" a bit across rows and columns.
I saw someone made a chess board, and I think they resorted to doing some math and a custom layout, and I was hoping to avoid that this early in my project. :-/
f
you should be able to achieve this with rows and columns; if you want square boxes, use
aspectRatio
Copy code
@Preview(widthDp = 420)
@Composable
fun Grid() {
    Column(
        modifier = Modifier.fillMaxWidth()
    ) {
        repeat(8) { row ->
            Row(
                modifier = Modifier.fillMaxWidth()
            ) {
                repeat(8) { index ->
                    Box(
                        modifier = Modifier
                            .weight(1f)
                            .aspectRatio(1f)
                            .background(
                                if (index % 2 == 0) Color.Red else Color.Blue
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = (row * index).toString()
                        )
                    }
                }
            }
        }
    }
}
t
Hmm... but you see how there are random gaps in some of the columns in the screenshot there?
Here's a screenshot of mine showing the problem as well. (I've currently got buttons in there, although something else may be more appropriate.)
Oh well. I guess I can keep working on the rest of the application for now and figure out proper alignment later. :-)
p
Column(Modifier.aspectRatio(1f)) { repeat(5) { Row(Modifier.weight(1f).fillMaxWidth()) { repeat(5) { Box(Modifier.weight(1).fillMaxHeight()){ // cell here } } } } }
t
I don't think that works either, for various screen shapes and sizes.
For now I'm just going to use
Modifier.size(50.dp)
for the cells, and multiples of that for the grid.
It's going to cause problems later for collapsed borders and so for, but it works for now -- and also solves the problem of the grid taking up the entire screen.