Last active
October 28, 2021 12:02
-
-
Save GregKluska/d7e9909c8313ff15a8effc42207246c5 to your computer and use it in GitHub Desktop.
Grid Layout for Compose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import androidx.compose.foundation.layout.Column | |
| import androidx.compose.foundation.layout.Row | |
| import androidx.compose.runtime.Composable | |
| import androidx.compose.ui.Modifier | |
| import kotlin.math.ceil | |
| @Composable | |
| fun GridLayout( | |
| modifier: Modifier = Modifier, | |
| rowModifier: Modifier = Modifier, | |
| cellModifier: Modifier = Modifier, | |
| columns: Int, | |
| content: GridLayoutScope.() -> Unit | |
| ) { | |
| val scope = GridLayoutScopeImpl().apply(content) | |
| val items = scope.list | |
| if (items.isEmpty()) return | |
| val rowCount: Int = ceil(items.size.toDouble() / columns).toInt() | |
| var currentId = 0 | |
| Column( | |
| modifier = modifier | |
| ) { | |
| for (i in 1..rowCount) { | |
| Row( | |
| modifier = rowModifier | |
| ) { | |
| while (currentId < items.size) { | |
| val inRow: Int = ceil((currentId + 1).toDouble() / columns).toInt() | |
| if (inRow != i) break | |
| Column( | |
| modifier = Modifier.weight(0.5F).then(cellModifier) | |
| ){ | |
| items[currentId].content() | |
| } | |
| currentId += 1 | |
| } | |
| } | |
| } | |
| } | |
| } | |
| interface GridLayoutScope { | |
| fun item(content: @Composable () -> Unit) | |
| } | |
| class GridLayoutScopeImpl : GridLayoutScope { | |
| val list: MutableList<GridItem> = mutableListOf() | |
| override fun item(content: @Composable () -> Unit) { | |
| list.add(GridItem(content = content)) | |
| } | |
| } | |
| data class GridItem( | |
| val content: @Composable () -> Unit | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment