Search code examples
androidandroid-jetpack-compose

How can I display horizontal and vertical dividers between items in the LazyVerticalGrid?


How can I display vertical and horizontal dividers between items in the LazyVerticalGrid?

For LazyColumn it is possible to do it this way:

LazyColumn(...) {
    items(items) { item ->
        Row(item)
        Divider()
    }
}

and it will also work for LazyVerticalGrid but I'm unsure how to display vertical dividers between items?


Solution

  • You can add a 2 different Dividers in each cell.

    Something like:

    val numbers = (0..20).toList()
    
    LazyVerticalGrid(cells = GridCells.Fixed(4)){
        itemsIndexed(numbers) { index, item ->
    
            Row(Modifier.height(IntrinsicSize.Min)) {
    
                Column(Modifier.weight(1f),horizontalAlignment = Alignment.CenterHorizontally) {
                    Text(text = "Number")
                    Text(text = "  $item",)
                    Divider() //Horizontal divider 
                }
                
                //Vertical divider avoiding the last cell in each row
                if ((index+1)%4 != 0) {
                    Column() {
                        Divider(
                            color = Color.Red,
                            modifier = Modifier
                                .fillMaxHeight()
                                .width(1.dp)
                        )
                    }
                }
            }
        }
    }
    

    enter image description here