Kotlin with Jetpack Compose -GridView
--
Grid view is an important UI that we use in mobile development.
Lazy grids
In Jetpack compose we have LazyVerticalGrid
and LazyHorizontalGrid
composables to display items in a grid. With LazyVerticalGrid we can scroll items vertically and with LazyHorizontalGrid we can scroll items horizontally.
In this article I will create an example using LazyVerticalGrid
.
LazyVerticalGrid properties
fun LazyVerticalGrid(
columns: GridCells,
modifier: Modifier = Modifier,
state: LazyGridState = rememberLazyGridState(),
contentPadding: PaddingValues = PaddingValues(0.dp),
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalArrangement: Arrangement.Horizontal = Arrangement.Start,
flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(),
userScrollEnabled: Boolean = true,
content: LazyGridScope.() -> Unit
)
Create a grid item list
You can create a custom GridItem data class with the desired properties. And then make a list with dummy data.
data class GridItem(
val id: Int,
val title: String,
val subtitle: String,
val imageUrl: String
)
val gridItemsList = listOf(
GridItem(1, "Item 1", "Subtitle for item 1", "http://eyesofwild.com/wp-content/uploads/photo-gallery/imported_from_media_libray/yau16-23.jpg"),
GridItem(2, "Item 2", "Subtitle for item 2", "http://eyesofwild.com/wp-content/uploads/photo-gallery/imported_from_media_libray/yfb17-4.jpg"),
GridItem(3, "Item 3", "Subtitle for item 3", "http://eyesofwild.com/wp-content/uploads/photo-gallery/imported_from_media_libray/ya16-27.jpg"),
GridItem(4, "Item 4", "Subtitle for item 4", "http://eyesofwild.com/wp-content/uploads/photo-gallery/imported_from_media_libray/yfb17-36.jpg")
)
Create a custom grid item view
You can create this with a matching ui for your requirement. This is the function that I created with an Image and two Text views.
@Composable
fun GridItemView(item: GridItem) {
Column(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
) {…