How do i create Gridview with Jetpack compose

Last updated Dec 15, 2021

In this Jetpack compose tutorial we will learn How to create Gridview in Android application using Jetpack Compose. 

In general Grid component will arrange the child items in two dimensional scrolling.

Jetpack Compose GridView Example

Let's get started

Step 1: Create android application in android studio

Step 2: Follow step for setup Jetpack Compose with Android Studio

 

To create Gridview we will use LazyVerticalGrid compose function

LazyVerticalGrid( cells = GridCells.Fixed(2) )

 

here we passed the grid cell count as 2 using cells  property

 

 

Example code to create GridView with Jetpack compose

package com.example.jetpack

import android.os.Bundle
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.jetpack.ui.theme.JetPackTheme

class MainActivity : ComponentActivity() {

    @ExperimentalFoundationApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        setContent {
            GridViewDemo()
        }
    }
}

@ExperimentalFoundationApi
@Composable
fun GridViewDemo() {
    val numbers = (1..30).toList()
    JetPackTheme(
        darkTheme = true,
    ) {
        Scaffold(content = {
            LazyVerticalGrid(
                cells = GridCells.Fixed(2)
            ) {
                items(numbers.size) {
                    Card(content = {
                        Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 16.dp)) {
                            Text(text = "  ${it+1}")
                        }
                    }, modifier = Modifier.padding(start = 16.dp, top = 16.dp))

                }
            }
        }, topBar = {
            TopAppBar(title = { Text("Grid View Demo") }
            )
        })
    }

}


@ExperimentalFoundationApi
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    GridViewDemo()
}

 

 

 

Images

Jetpack Compose GridView Example

 

Conclusion: In this Jetpack compose tutorial we create Simple Gridview with two columns

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

572 Views