GridView and LazyColum Integration With Jetpack Compose

Build amazing grid layouts in Android

Enes Kayıklık
Better Programming

--

Photo by Sharon McCutcheon on Unsplash

LazyVerticalGrid is a very useful component if you want to add a grid view to your app.

Unluckily, it can’t be placed inside another vertical scrollable container since it has vertical scroll behavior.

If you try to join the LazyColumn with LazyVerticalGrid, you are going to see the following exception:

java.lang.IllegalStateException: Vertically scrollable component was measured with an infinity maximum height constraints, which is disallowed. One of the common reasons is nesting layouts like LazyColumn and Column(Modifier.verticalScroll()). If you want to add a header before the list of items please add a header as a separate item() before the main items() inside the LazyColumn scope. There are could be other reasons for this to happen: your ComposeView was added into a LinearLayout with some weight, you applied Modifier.wrapContentSize(unbounded = true) or wrote a custom layout. Please try to remove the source of infinite constraints in the hierarchy above the scrolling container.

In this article, we are going to fix this issue and make the whole screen scrollable.

In my WallUp application, I have a HomeScreen that shows several items. Some of them are grid some of them not. When I try to implement this screen in the app I encountered the above issue.

I wanted the whole screen to be scrollable with grid items but I couldn’t merge LazyGridView with LazyColumn.

Workaround

After thinking for a while, it occurred to me that all items in the grid structure are divided into rows. So we can implement this structure using Row Composable.

Implementation

First of all, we need to add gridItems extension function to our app.

"data" is a list of items that we are going to display as a grid. "columnColunt" is a count of grid inside Row.

Now we can use grid items inside LazyColumn like below:

Conclusion

In this short article, we looked at the LazyVerticalGrid and vertical scroll issue with other vertical scrollable composables.

We saw that trying to join the composable with other vertical scrollable composables caused an app crash.

As a workaround, we fixed this using Row composable.

I hope you had some takeaways, see you in other articles.

--

--