Skip to content

Instantly share code, notes, and snippets.

@rahulsainani
Last active October 30, 2021 18:24
Show Gist options
  • Save rahulsainani/f7e4290cbce307cbb6dbca5f4f753d74 to your computer and use it in GitHub Desktop.
Save rahulsainani/f7e4290cbce307cbb6dbca5f4f753d74 to your computer and use it in GitHub Desktop.
LazyGrid implementation in Compose Foundation
@ExperimentalFoundationApi
@Composable
fun LazyVerticalGrid(
cells: GridCells,
modifier: Modifier = Modifier,
state: LazyListState = rememberLazyListState(),
contentPadding: PaddingValues = PaddingValues(0.dp),
content: LazyGridScope.() -> Unit
) {
val scope = LazyGridScopeImpl()
scope.apply(content)
when (cells) {
is GridCells.Fixed ->
FixedLazyGrid(
nColumns = cells.count,
modifier = modifier,
state = state,
contentPadding = contentPadding,
scope = scope
)
is GridCells.Adaptive ->
BoxWithConstraints(
modifier = modifier
) {
val nColumns = maxOf((maxWidth / cells.minSize).toInt(), 1)
FixedLazyGrid(
nColumns = nColumns,
state = state,
contentPadding = contentPadding,
scope = scope
)
}
}
}
@ExperimentalFoundationApi
sealed class GridCells {
@ExperimentalFoundationApi
class Fixed(val count: Int) : GridCells()
/**
* Combines cells with adaptive number of rows or columns. It will try to position as many rows
* or columns as possible on the condition that every cell has at least [minSize] space and
* all extra space distributed evenly.
*
* For example, for the vertical [LazyVerticalGrid] Adaptive(20.dp) would mean that there will be as
* many columns as possible and every column will be at least 20.dp and all the columns will
* have equal width. If the screen is 88.dp wide then there will be 4 columns 22.dp each.
*/
@ExperimentalFoundationApi
class Adaptive(val minSize: Dp) : GridCells()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment