How to create GridView using Jetpack Compose

How to create GridView using Jetpack Compose. GridView is a grid-based form of view where the items in the grid are laid out in a grid arrangement. The information within the grid must be imported either from the database or an array. In this post, we’ll create a basic application to display the various programming languages in the grid, and displaying them with their names by using Jetpack Compose.

InThis Android jetpack compose article I am creating a project to showing list date in gridview in jetpack comapose and when click on card navigation to details screen.

How to create GridView using Jetpack Compose

Step-by-Step Implementation GridView using Jetpack Compose

First, create a new Android Studio Project. Android Studio

To start a new project using Android Studio Please refer to How to Start with a new Project within Android Studio. After selecting the template, choose an empty compose activity. If you are unable to locate this template, you can consider upgrading Android Studio to the latest version. We have demonstrated the app in Kotlin which is why you choose Kotlin as as the primary language when creating an New Project.

Dependencies

dependencies {
    /**first we add dependencies */

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
    implementation 'androidx.activity:activity-compose:1.4.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

    //Gson
    implementation 'com.google.code.gson:gson:2.8.7'

     //Navigate
    implementation "androidx.navigation:navigation-compose:2.4.0-alpha08"


}

2. Creating an modal class

Browse to the app’s menu, Java > the name of your app’s package Then right-click it and choose New > Java/Kotlin Class and label your class as GridModal and add the following instructions to the class. Comments are included in the code for you to understand the code in greater detail.

package com.codeplayon.gridlayout.model

data  class FruitsData(
    val id:Long,
    val name :String,
    val desc :String
)

 

Step 3. Adding a new color to the Color.kt file

Go to the app, click Java > the name of your app’s package >> ui.theme Then, open the Color.kt file. Add the following code.

step 4: Add photos to the folder that can be drawn

Copy all images that you would like to include to the view grid. Go to the app, Res > Drawable. Right-click and copy all images into the folder for drawable.

Step 5: Create a FruitDataDetails.kt file for date parser.

package com.codeplayon.gridlayout.view

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.codeplayon.gridlayout.model.FruitsData
import com.codeplayon.gridlayout.ui.theme.Purple500
import com.codeplayon.gridlayout.R

@Composable
fun FruitsDataDetails(data:FruitsData){

    Column(modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Column(modifier = Modifier.fillMaxWidth()
            .height(50.dp)
            .background(Purple500),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Text(
                text ="Fruits Calories and Sugar",
                color = Color.White,
                fontSize =  20.sp,
                fontWeight = FontWeight.Bold
            )

        }
        Spacer(modifier = Modifier.padding(1.dp))
        Image(painter = painterResource(
            id =  when(data.id){
                1L-> R.drawable.apple_min
                2L -> R.drawable.banana_min
                3L -> R.drawable.orange_min
                4L -> R.drawable.grapes_min
                5L -> R.drawable.pomegranate_min
                6L -> R.drawable.kiwifruit_min
                7L -> R.drawable.papaya_min
                8L -> R.drawable.pineapple_min
                9L -> R.drawable.avocado_min
                10L -> R.drawable.peach_min
                11L-> R.drawable.apple_min
                12L -> R.drawable.banana_min
                13L -> R.drawable.orange_min
                14L -> R.drawable.grapes_min
                15L -> R.drawable.pomegranate_min
                16L -> R.drawable.kiwifruit_min
                17L -> R.drawable.papaya_min
                18L -> R.drawable.pineapple_min
                19L -> R.drawable.avocado_min
                else -> R.drawable.apple_min
            }
        ),
            contentDescription = "Grid Image",
            modifier = Modifier
                .clip(RoundedCornerShape(10.dp)),
            alignment = Alignment.Center
        )
        Spacer(modifier = Modifier.padding(10.dp))
        Text(
            text = data.name,
            modifier = Modifier
                .align(Alignment.CenterHorizontally),
            color = Color.Black,
            fontSize =  20.sp,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.padding(1.dp))

        Text(
            text = data.desc,
            modifier = Modifier
                .align(Alignment.Start)
                .padding(6.dp),
            color = Color.Black,
            fontSize =  16.sp,
            fontWeight = FontWeight.Normal,


        )
    }


}

Step 6: Create FruitsGridLayout.kt file and user below code.

Hare we are create a card view for shiwing date GridView using Jetpack Compose.

package com.codeplayon.gridlayout.view

import android.content.Context
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.codeplayon.gridlayout.model.FruitsData
import com.codeplayon.gridlayout.ui.theme.Purple500
import com.codeplayon.gridlayout.R

@ExperimentalFoundationApi
@Composable
fun FruitGrid(navController : NavController){

    val context = LocalContext.current
    val dataFileString = getJsonDataFromAsset(context,"FruitsList.json")
    val gson = Gson()
    val gridSampleType = object :TypeToken<List<FruitsData>>(){}.type
    val fruitData : List<FruitsData> = gson.fromJson(dataFileString,gridSampleType)

    Column(modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Column(modifier = Modifier
            .fillMaxWidth()
            .height(50.dp)
            .background(color = Purple500)
            .padding(6.dp),
            horizontalAlignment = Alignment.Start,
            verticalArrangement = Arrangement.Center
        ) {
            Text(
                text ="Fruits Calories and Sugar",
                color = Color.White,
                fontSize =  20.sp,
                fontWeight = FontWeight.Bold
            )
        }
        LazyVerticalGrid(
            cells = GridCells.Fixed(3),
          modifier = Modifier.padding(10.dp)
        ){
            items(fruitData){data->
                FruitDataGridItem(data,navController)

            }

        }

    }



}

@Composable
fun FruitDataGridItem(data:FruitsData,navController :NavController){

    Card(modifier = Modifier
        .clickable {
            val itemVal = Gson().toJson(data)
            navController.navigate("grid_detail/$itemVal")
        }
        .padding(10.dp)
        .fillMaxSize(),
        elevation =  5.dp,
        shape = RoundedCornerShape(5.dp)
    ) {
        Column(modifier = Modifier) {
            Image(painter = painterResource(
                id =  when(data.id){
                    1L-> R.drawable.apple_min
                    2L -> R.drawable.banana_min
                    3L -> R.drawable.orange_min
                    4L -> R.drawable.grapes_min
                    5L -> R.drawable.pomegranate_min
                    6L -> R.drawable.kiwifruit_min
                    7L -> R.drawable.papaya_min
                    8L -> R.drawable.pineapple_min
                    9L -> R.drawable.avocado_min
                    10L -> R.drawable.peach_min
                    11L-> R.drawable.apple_min
                    12L -> R.drawable.banana_min
                    13L -> R.drawable.orange_min
                    14L -> R.drawable.grapes_min
                    15L -> R.drawable.pomegranate_min
                    16L -> R.drawable.kiwifruit_min
                    17L -> R.drawable.papaya_min
                    18L -> R.drawable.pineapple_min
                    19L -> R.drawable.avocado_min
                    else -> R.drawable.apple_min
                }
            ),
                contentDescription = "Grid Image",
                modifier = Modifier
                    .fillMaxSize()
                    .align(Alignment.CenterHorizontally)
                    .clip(RoundedCornerShape(5.dp)),
                alignment = Alignment.Center
            )
            Spacer(modifier = Modifier.padding(3.dp))
            Text(
                text = data.name,
                modifier = Modifier
                    .align(Alignment.CenterHorizontally),
                fontSize =  15.sp,
                fontWeight = FontWeight.Bold,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Spacer(modifier = Modifier.padding(1.dp))
            Text(
                text = data.desc,
                modifier = Modifier
                    .padding(7.dp,0.dp,0.dp,20.dp)
                ,
                fontSize =  13.sp,
                fontWeight = FontWeight.Normal,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis

            )


        }

    }



}

fun getJsonDataFromAsset(context: Context, data: String):String {
    return context.assets.open(data).bufferedReader().use { it.readText() }

}

 

Step 7: Working using MainActivity.kt file MainActivity.kt File

Visit go to the MainActivity.ktfile and refer to the following code. The code below is for MainActivity.kt file. Comments are included within the code to explain the code more in depth. GridView using Jetpack Compose.

package com.codeplayon.gridlayout

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navArgument
import androidx.navigation.compose.rememberNavController
import com.google.gson.Gson
import com.codeplayon.gridlayout.model.FruitsData
import com.codeplayon.gridlayout.ui.theme.GridLayoutExampleTheme
import com.codeplayon.gridlayout.view.FruitGrid
import com.codeplayon.gridlayout.view.FruitsDataDetails

class MainActivity : ComponentActivity() {

    @ExperimentalFoundationApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            GridLayoutExampleTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    /** ok now call fun NavigatePage*/
                    NavigatePage()

                }
            }
        }
    }
}

@ExperimentalFoundationApi
@Composable
fun NavigatePage(){

    val navHostController = rememberNavController()


    NavHost(
        navController = navHostController,
       startDestination = "fruits_data"
    ){
        composable("fruits_data"){
            FruitGrid(navController = navHostController)
        }
        composable("grid_detail/{item}",
            arguments = listOf(
                navArgument("item"){
                    type = NavType.StringType
                }
            )
        ){navBackStackEntry ->

            navBackStackEntry?.arguments?.getString("item")?.let { json->
                val item = Gson().fromJson(json,FruitsData::class.java)
                FruitsDataDetails(data = item)

            }
        }
    }



}



@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    GridLayoutExampleTheme {
        Greeting("Android")
    }
}

Run your program to check the output of it.

 

Read More Tutorial 

You may also like...