androidandroid-jetpack-composeandroid-jetpack-compose-list

How to create GridView using Jetpack Compose


How to create Gridview in Jetpack compose without using recycler view or android.widget.gridview ?


Solution

  • With 1.x.y the LazyVerticalGrid composable provides experimental support for displaying items in a grid.

    val numbers = (0..20).toList()
    
    LazyVerticalGrid(
        columns = GridCells.Fixed(4)
    ) {
        items(numbers.size) {
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Text(text = "Number")
                Text(text = "  $it",)
            }
        }
    }
    

    The columns = GridCells.Fixed(4) would mean that there are 4 columns 1/4 of the parent wide.

    enter image description here

    val numbers = (0..20).toList()
    
    LazyVerticalGrid(
        columns = GridCells.Adaptive(minSize = 64.dp)
    ) {
        items(numbers) {
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Text(text = "Number")
                Text(text = "  $it",)
            }
        }
    }
    

    columns = GridCells.Adaptive(minSize = 64.dp) would mean that there will be as many columns as possible and every column will be at least 64.dp and all the columns will have equal width.

    enter image description here