Grid and Lists in Compose
Tags: android, kotlin, tutorial, beginners
Published: 2023-07-07 15:30:17

Hello, there! I hope you’re doing well!

Many times, we need to display collections in our apps, and to accomplish that, we can use list and grid layouts.
&nbsp;
## Grid vs List
&nbsp;
## Grid
&nbsp;
To create grid layouts, you can use LazyVerticalGrid to display items in a vertically scrollable container, while LazyHorizontalGrid will exhibit the same behavior along the horizontal axis.
&nbsp;
To utilize Lazy Grids, specify the number of columns (for vertical grids) or rows (for horizontal grids) as a parameter:
```kotlin
LazyVerticalGrid(
    columns = GridCells.Adaptive(minSize = 100.dp)
) {
    items(images) { image ->
        ImageItem(image)
    }
}
```
&nbsp;
If you pay attention, we’re using the **GridCells.Adaptive** approach, which is useful for displaying sets of items across different screen sizes.Alternatively, you can utilize **GridCells.Fixed** if you know the exact number of columns to be used.
&nbsp;

>For further customization, the **GridCells** offer a single function, **calculateCrossAxisCellSizes**, allowing you to combine adaptive and fixed implementations.

&nbsp;
To display a **Lazy Staggered Grid**, use columns (for a vertical layout) or rows (for a horizontal layout) as parameters, similar to the Lazy Grid. This composable enables you to create a lazy-loaded, staggered grid of items:
&nbsp;
Import the dependencies in your build.gradle (module).

```kotlin
implementation 'androidx.compose.foundation:foundation:1.3.0'
```
&nbsp;
```kotlin
LazyVerticalStaggeredGrid(
    columns = StaggeredGridCells.Adaptive(200.dp),
    verticalItemSpacing = 8.dp,
    horizontalArrangement = Arrangement.spacedBy(8.dp),
    content = {
        items(images) { image ->
            AsyncImage(
                model = image,
                contentScale = ContentScale.Crop,
                contentDescription = "Description of the image",
                modifier = Modifier.fillMaxWidth().wrapContentHeight()
            )
        }
    },
    modifier = Modifier.fillMaxSize()
)
```
&nbsp;
You can also use a different parameter with the **StaggeredGridCells** in the same way as the GridCells.
&nbsp;
## List
&nbsp;
To create a list of items, you can utilize **LazyList**. You can display both horizontal and vertical lists by using **LazyColumn** and **LazyRow**, respectively.
&nbsp;
```kotlin
LazyColumn {
    // Add a single item
    item {
        Text(text = "First item")
    }

    // Add 8 items
    items(8) { index ->
        Text(text = "Item: $index")
    }

    items(imageList) { image ->
        ImageItem(image)
    }
}
```
&nbsp;
Or you can use **LazyRows**:
&nbsp;
```kotlin
LazyRow(
   verticalArrangement = Arrangement.spacedBy(16.dp),
) {
    // ...
}
```
&nbsp;
## Exemple
Now let’s create an sample of a **Grid** and **List** layout that shows a name and an image:
&nbsp;
I created an composable function called ListLayout:
&nbsp;
```kotlin
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ListAndGridTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    ListLayout()
                }
            }
        }
    }
}
```
&nbsp;
And create a mutable list that needs a name and an image:
&nbsp;
```kotlin
val itemList = mutableListOf(
    Item(R.drawable.ic_android_black_24dp, "Ada Lovelace"),
    Item(R.drawable.ic_android_black_24dp, "Mary Kenneth"),
    Item(R.drawable.ic_android_black_24dp, "Grace Hopper"),
    Item(R.drawable.ic_android_black_24dp, "Carol Shaw"),
    Item(R.drawable.ic_android_black_24dp, "Hedy Lamarr"),
    Item(R.drawable.ic_android_black_24dp, "Camila Achutti"),
    Item(R.drawable.ic_android_black_24dp, "Cláudia Marquesani")
)
```
&nbsp;
Let’s call the LazyColumn function that we learn before and pass the list as parameter:
&nbsp;
```kotlin
LazyColumn {
    items(itemList) { image ->
    }
}
```
&nbsp;
And create a layout to our item:
&nbsp;
```kotlin
Column(
    modifier = Modifier
        .fillMaxSize()
        .padding(start = 16.dp, end = 16.dp, top = 16.dp)
) {
    LazyColumn {
        items(androidIconList) { image ->
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight(),
                backgroundColor = Color(0xFFEBF7FE),
                elevation = 4.dp,
                shape = RoundedCornerShape(size = 12.dp)
            ) {
                Row(
                    Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Image(
                        painter = painterResource(id = image.image),
                        contentDescription = "Avatar icon",
                        modifier = Modifier
                            .size(100.dp)
                            .padding(start = 16.dp)
                    )
                    Text(
                        text = image.name,
                        fontSize = 24.sp,
                        modifier = Modifier.padding(start = 16.dp)
                    )
                }
            }
            Spacer(modifier = Modifier.height(8.dp))
        }
    }
}
```
&nbsp;
Now the Grid layout:
&nbsp;
With the same list, we’re gonna to create another function to display our grid layout. I’m gonna use the **Staggered**:
&nbsp;
```kotlin
LazyVerticalStaggeredGrid(
    columns = StaggeredGridCells.Fixed(2)
) {
    items(androidIconList) { image ->
    }
}
```
&nbsp;
And create a layout to our cells:
&nbsp;
```kotlin
Column(
    modifier = Modifier
        .fillMaxSize()
        .padding(start = 16.dp, end = 16.dp, top = 16.dp)
) {
    LazyVerticalStaggeredGrid(
        columns = StaggeredGridCells.Fixed(2),
        contentPadding = PaddingValues(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp),
        horizontalArrangement = Arrangement.spacedBy(16.dp)
    )
    {
        items(androidIconList) { image ->
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight(),
                backgroundColor = Color(0xFFEBF7FE),
                elevation = 4.dp,
                shape = RoundedCornerShape(size = 12.dp)
            ) {
                Column(
                    Modifier.fillMaxWidth()
                ) {
                    Image(
                        painter = painterResource(id = image.image),
                        contentDescription = "Avatar icon",
                        modifier = Modifier
                            .size(100.dp)
                            .padding(start = 16.dp)
                    )
                    Text(
                        text = image.name,
                        fontSize = 24.sp,
                        modifier = Modifier.padding(start = 16.dp)
                    )
                }
            }
        }
    }
}
```
&nbsp;
The [complete code is available](https://github.com/MariaLuiza-CS/GridAndListCompose) in this repository on my GitHub profile.
&nbsp;
Hope you guys could see how easy it is to display Lists and Grid layouts using Jetpack Compose and how we can optimize our time when developing Android screens with Compose 😊
&nbsp;
Please let me know what you think in the comments…
&nbsp;
Connect with me 👇

[Linkedin](https://www.linkedin.com/in/marialuiza-cs/)

[GitHub](https://github.com/MariaLuiza-CS)