Open In App

Staggered GridView in Android using Jetpack Compose

Last Updated : 06 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Staggered Grid View has been seen in most applications such as Pinterest in which each item of grid view takes its own height and aligns within the grid view according to that. In this article, we will look at how to implement Staggered Grid View in Android using Jetpack Compose

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding a new color in the Color.kt file

Navigate to the app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it. 

Kotlin




package com.example.newcanaryproject.ui.theme
 
import androidx.compose.ui.graphics.Color
 
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
 
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)


Step 3: Adding images to the drawable folder

Copy all the images which you want to add to your grid view. Navigate to app > res > drawable. Right-click on it and paste all the images into the drawable folder.

Step 4: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.example.newcanaryproject
 
import android.content.Context
import android.os.Bundle
 
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.Layout
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.TextAlign
import androidx.compose.ui.unit.*
import coil.compose.rememberAsyncImagePainter
import com.example.newcanaryproject.ui.theme.*
import java.util.*
 
class MainActivity : ComponentActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying
                // background color for our application
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    // on below line we are specifying theme as scaffold.
                    Scaffold(
                        // in scaffold we are specifying top bar.
                        topBar = {
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
                                // along with that we are specifying title for our top bar.
                                title = {
                                    // in the top bar we are specifying tile as a text
                                    Text(
                                        // on below line we are specifying
                                        // text to display in top app bar.
                                        text = "Staggered Grid View Example",
                                         
                                        // on below line we are specifying
                                        // modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
                                         
                                        // on below line we are specifying text alignment.
                                        textAlign = TextAlign.Center,
                                         
                                        // on below line we are specifying
                                        // color for our text.
                                        color = Color.White
                                    )
                                }
                            )
                        }
                    ) {
                        // on below line we are calling custom list
                        // view function to display custom listview.
                        StaggeredGridView()
                    }
                }
            }
        }
    }
}
 
@Composable
fun StaggeredGridView() {
        // on below line we are creating
        // an array of images.
        val images = listOf(
        R.drawable.imgone,
        R.drawable.imgtwo,
        R.drawable.imgthree,
        R.drawable.imgfour,
        R.drawable.imgfive,
        R.drawable.imgsix,
        R.drawable.imgseven,
        R.drawable.imgeight,
        R.drawable.imgnine,
        R.drawable.imgten
    )
 
    // on below line we are creating a column
    // for our staggered grid view.
    Column(
        // for this column we are adding a
        // modifier to it to fill max size.
        modifier = Modifier
            .fillMaxSize()
    ) {
        // on below line we are creating a column
        // for each item of our staggered grid.
        Column(
            // in this column we are adding modifier to it
            // and adding padding from all sides and vertical scroll.
            modifier = Modifier
                .verticalScroll(rememberScrollState())
                .padding(5.dp)
        ) {
            // on below line we are calling our
            // custom staggered vertical grid item.
            CustomStaggeredVerticalGrid(
                // on below line we are specifying
                // number of columns for our grid view.
                numColumns = 2,
                 
                // on below line we are adding padding
                // from all sides for our grid view.
                modifier = Modifier.padding(5.dp)
            ) {
                // inside staggered grid view we are
                // adding images for each item of grid.
                images.forEach { img ->
                    // on below line inside our grid
                    // item we are adding card.
                    Card(
                        // on below line inside the card we
                        // are adding modifier to it to specify
                        // max width, padding, elevation and shape for the card
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(5.dp),
                        elevation = 10.dp,
                        shape = RoundedCornerShape(10.dp)
                    ) {
                        // on below line we are adding column inside our card.
                        Column(
                            // in this column we are adding modifier
                            // to fill max size and align our
                            // card center horizontally.
                            modifier = Modifier
                                .fillMaxSize()
                                .align(Alignment.CenterHorizontally),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            // inside our column we are creating an image.
                            Image(
                                // on below line we are specifying the
                                // drawable image for our image.
                                painterResource(id = img),
                                 
                                // on below line we are specifying
                                // content description for our image
                                contentDescription = "images",
                                 
                                // on below line we are specifying
                                // alignment for our image.
                                alignment = Alignment.Center,
                            )
                        }
                    }
                }
            }
        }
    }
}
 
// on below line we are creating a custom
// composable item for our grid view item.
@Composable
fun CustomStaggeredVerticalGrid(
    // on below line we are specifying
    // parameters as modifier, num of columns
    modifier: Modifier = Modifier,
    numColumns: Int = 2,
    content: @Composable () -> Unit
) {
    // inside this grid we are creating
    // a layout on below line.
    Layout(
        // on below line we are specifying
        // content for our layout.
        content = content,
        // on below line we are adding modifier.
        modifier = modifier
    ) { measurable, constraints ->
        // on below line we are creating a variable for our column width.
        val columnWidth = (constraints.maxWidth / numColumns)
         
        // on the below line we are creating and initializing our items constraint widget.
        val itemConstraints = constraints.copy(maxWidth = columnWidth)
         
        // on below line we are creating and initializing our column height
        val columnHeights = IntArray(numColumns) { 0 }
         
        // on below line we are creating and initializing placeables
        val placeables = measurable.map { measurable ->
            // inside placeable we are creating
            // variables as column and placeables.
            val column = testColumn(columnHeights)
            val placeable = measurable.measure(itemConstraints)
             
            // on below line we are increasing our column height/
            columnHeights[column] += placeable.height
            placeable
        }
 
        // on below line we are creating a variable for
        // our height and specifying height for it.
        val height =
            columnHeights.maxOrNull()?.coerceIn(constraints.minHeight, constraints.maxHeight)
                ?: constraints.minHeight
 
        // on below line we are specifying height and width for our layout.
        layout(
            width = constraints.maxWidth,
            height = height
        ) {
            // on below line we are creating a variable for column y pointer.
            val columnYPointers = IntArray(numColumns) { 0 }
             
            // on below line we are setting x and y for each placeable item
            placeables.forEach { placeable ->
                // on below line we are calling test
                // column method to get our column index
                val column = testColumn(columnYPointers)
 
                placeable.place(
                    x = columnWidth * column,
                    y = columnYPointers[column]
                )
                
                // on below line we are setting
                // column y pointer and incrementing it.
                columnYPointers[column] += placeable.height
            }
        }
    }
}
 
// on below line we are creating a test column method for setting height.
private fun testColumn(columnHeights: IntArray): Int {
    // on below line we are creating a variable for min height.
    var minHeight = Int.MAX_VALUE
     
    // on below line we are creating a variable for column index.
    var columnIndex = 0
     
    // on below line we are setting column  height for each index.
    columnHeights.forEachIndexed { index, height ->
        if (height < minHeight) {
            minHeight = height
            columnIndex = index
        }
    }
    // at last we are returning our column index.
    return columnIndex
}


Run your application to see the output of it. 

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads