'How to create GridView using Jetpack Compose
How to create Gridview in Jetpack compose without using recycler view or android.widget.gridview ?
Solution 1:[1]
With 1.0.x
the LazyVerticalGrid
composable provides experimental support for displaying items in a grid.
val numbers = (0..20).toList()
LazyVerticalGrid(
cells = GridCells.Fixed(4)
) {
items(numbers.size) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = "Number")
Text(text = " $it",)
}
}
}
The cells = GridCells.Fixed(4)
would mean that there are 4 columns 1/4 of the parent wide.
val numbers = (0..20).toList()
LazyVerticalGrid(
cells = GridCells.Adaptive(minSize = 64.dp)
) {
items(numbers) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = "Number")
Text(text = " $it",)
}
}
}
cells = GridCells.Adaptive(minSize = 64.dp)
would mean that there will be as many columns as possible and every column will be at least 64.dp and all the columns will have equal width.
Solution 2:[2]
UPD: Compose version 1.0.0-alpha09 introduces standard component:
LazyVerticalGrid
Yet another solution based on LazyColumnFor (Jetpack Compose version 1.0.0-alpha04)
@Composable
fun <T> LazyGridFor(
items: List<T>,
rowSize: Int = 1,
itemContent: @Composable BoxScope.(T) -> Unit,
) {
val rows = items.chunked(rowSize)
LazyColumnFor(rows) { row ->
Row(Modifier.fillParentMaxWidth()) {
for ((index, item) in row.withIndex()) {
Box(Modifier.fillMaxWidth(1f / (rowSize - index))) {
itemContent(item)
}
}
}
}
}
@Preview("LazyGridFor: example")
@Composable()
fun LazyGridForPreview() {
val data = (1..100).map(Integer::toString)
LazyGridFor(data, 3) { item ->
Text(item)
}
}
Solution 3:[3]
As @Pavel Marchenko mentioned, LazyVerticalGrid
is added from version 1.0.0-alpha09
Here is a quick example:
LazyVerticalGrid(
cells = GridCells.Adaptive(96.dp),
contentPadding = PaddingValues(16.dp),
) {
items(bookList) { book ->
Image(book.cover, modifier = Modifier.padding(8.dp))
}
}
Solution 4:[4]
I have created a adaptative grid layout:
Preveiw
Code
LazyColumn(modifier = modifier) {
...
val numberOfItemsByRow = LocalConfiguration.current.screenWidthDp / 200 // you can replace 200 by the minimum size you want your cells to have.
items(items = trendingGameList.chunked(numberOfItemsByRow)) { rowItems ->
Row(
horizontalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.padding(horizontal = 16.dp),
) {
for (game in rowItems) {
GameCard(game = game, onClick = { }, modifier = Modifier.weight(1F))
}
}
Spacer(Modifier.height(14.dp))
}
...
}
The full code is here.
I decided to implement my own adaptative grid layout because the existing LazyVerticalGrid is experimental and can be removed in the future, and to use it you have to annotate the compostables that uses it with @ExperimentalFoundationApi
recursively:
@ExperimentalFoundationApi
@Composable
fun A {
LazyVerticalGrid {
...
}
}
@ExperimentalFoundationApi
@Composable
fun B {
A {..}
}
@ExperimentalFoundationApi
@Composable
fun C {
B {..}
}
...
OR use the @OptIn(ExperimentalFoundationApi::class)
which require the -Xopt-in=kotlin.RequiresOptIn
compiler argument.
Solution 5:[5]
Update to @Pavel Marchenko answer as some of the compose function's names changed: LazyColumn() instead of LazyColumnFor() and use of items() functions is needed:
@Composable
fun <T> LazyGridFor(
items: List<T>,
rowSize: Int = 1,
itemContent: @Composable BoxScope.(T) -> Unit,
) {
LazyColumn {
items(items = items.chunked(rowSize)) { row ->
Row(Modifier.fillParentMaxWidth()) {
for ((index, item) in row.withIndex()) {
Box(Modifier.fillMaxWidth(1f / (rowSize - index))) {
itemContent(item)
}
}
}
}
}
}
Solution 6:[6]
I have created a custom gridview for using android jetpack compose until they will not support official recycleview for Gridlayout in Compose.
@Composable
fun <T> GridView(
cols: Int = 0,
list: List<T>,
child: @Composable() (dataModal: T) -> Unit
) {
val rows = (list.size / cols) + (if (list.size % cols > 0) 1 else 0)
VerticalScroller(modifier =
Modifier.fillMaxHeight().fillMaxHeight().drawBackground(color = colorResource(
id = R.color.color_bg_application
))) {
Table(columns = cols) {
for (r in 0 until rows) {
tableRow {
for (c in 0 until cols) {
//Cell
val i = (r * cols) + c
if (i < list.size) {
child(list[i])
} else {
break
}
}
}
}
}
}
}
USE
GridView(cols = 4, list = model.list,child = { Item( it) })
Item declaration
@Composable
fun Item(t: T) {
....
}
Solution 7:[7]
Made a couple of changes to @Madhav 's answer (using compose v1.0.0-alpha01
):
@Composable
fun <T> GridView(
cols: Int = 1,
list: List<T>,
rowModifier: Modifier = Modifier,
colModifier: Modifier = Modifier,
child: @Composable (dataModal: T) -> Unit
) {
val rows = (list.size / cols) + (if (list.size % cols > 0) 1 else 0)
ScrollableColumn(modifier = colModifier) {
for (r in 0 until rows) {
Row(modifier = rowModifier, horizontalArrangement = Arrangement.SpaceAround) {
for (cell in 0 until cols) {
val i = (r * cols) + cell
if (i < list.size) { child(list[i]) } else { break }
}
}
}
}
}
Usage:
GridView(cols = 2, list = listOf("1", "2", "3", "4",)) {
Text(text = it)
}
Solution 8:[8]
Since LazyVerticalGrid can't be used in a LazyColumn, can't use it in a scrollable page. I created a library for custom LazyGrid implementation in compose. It's lazy so it performs really well. There are different item placement types for different scenarios and it's really easy to use:
LazyColumn {
item {
Text(text = "Title")
}
LazyGrid(
rows = listOf(),
elementPerRow = 4,
itemPlacementType = ItemPlacementType.FixedSize(itemWidth = 80.dp),
contentPadding = PaddingValues(horizontal = 16.dp)
) { item, modifier ->
CustomGridItem(item, modifier, onClick = { /* if needed */ })
}
}
There is also a collapsible version. Further information, documentation, source code and a demo can be found in: https://github.com/yusufarisoy/lazy-grid
dependencies {
implementation 'com.github.yusufarisoy:lazy-grid:1.0.0'
}
It's also restartable and skippable for compose compiler to work with best performance. About Compose metrics: https://chris.banes.dev/composable-metrics/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | AnT |
Solution 4 | |
Solution 5 | Krzysiulele |
Solution 6 | |
Solution 7 | Mahdi-Malv |
Solution 8 | yusufarisoy |