Open the Starter project in the 03-work-with-grids directory of the m3-ljp-materials repo in Android Studio Hedgehog or later.
Build and run the project.
In this lesson, you’ll create a scrolling grid of photos.
Open MainViewModel.kt. You’ll notice getPhotos, a function that fetches the list of photos from the repository and assigns them to the state.
You’ll use the state to render a photo grid on the screen.
Replace the TODO in MainActivity.kt with the following snippet:
LazyVerticalGrid(
columns = GridCells.Adaptive(80.dp),
modifier = Modifier.fillMaxSize(),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
}
In the snippet above, you first created a LazyVerticalGrid wrapper for the photo grid. You then specified the column configuration by using GridCells.Adaptive and set each column to take up at least 80dp.
You then specified the horizontalArrangement, where each item will be spaced 4dp apart, and similarly specified the verticalArrangement to space each item 4dp apart.
Next, add the following snippet to the body of the LazyVerticalGrid:
items(state) { photo ->
PhotoItem(photo)
}
In this snippet, you used the items receiver to accept the state as a parameter and render a PhotoItem for each photo on the list.
Build and run the project and you should see a grid of photos on the screen that you can scroll through vertically.
For an interesting effect, you can also try using the LazyVerticalStaggeredGrid here.
Modify the grid code as follows to use the LazyVerticalStaggeredGrid:
LazyVerticalStaggeredGrid(
modifier = Modifier.fillMaxSize(),
columns = StaggeredGridCells.Adaptive(80.dp),
verticalItemSpacing = 12.dp,
horizontalArrangement = Arrangement.spacedBy(8.dp),
content = {
items(state) { photo ->
PhotoItem(photo)
}
}
)
Build and run the app. You should now see a staggered masonry layout of the photos.
That concludes this demo. Continue with the lesson for a summary.