Android Jetpack

How to Implement Staggered Grid with Compose

Pinterest LinkedIn Tumblr

If you’re looking to create a staggered grid in compose for your android app, consider implementing a staggered grid layout. This layout allows for a more dynamic and interesting display of content, with varying sizes and positions of items. Follow this step-by-step guide to learn how to implement a staggered grid layout with jetpack compose in your Android app.

Understand the basics of staggered grid layout

Before diving into implementing a staggered grid layout in your Android app, it’s important to understand the basics of this layout. A staggered grid layout is a type of grid layout where items are positioned in a staggered pattern, with varying sizes and positions. Just like feature image.

Set up your project and add dependencies

The first step to implementing a staggered grid layout in your Android app is to set up your project and add the necessary dependencies. Which can be done by adding the following lines to your app-level build.gradle file

    implementation "androidx.compose.ui:ui:$compose_ui_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_ui_version"
    implementation 'androidx.compose.material:material:1.3.1'
    // For Image
    implementation("io.coil-kt:coil-compose:2.2.2")

Match the following lines to your project-level build.gradle file

buildscript {
    ext {
        compose_ui_version = '1.4.0-rc01'
    }
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.3.1' apply false
    id 'com.android.library' version '7.3.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.8.10' apply false
}

Once you have added these dependencies, you can start implementing the staggered grid layout in your app.

Create a data class for gird item

The first step in implementing a staggered grid layout in your Android app is to create a  data class which hold the information of gird item

package com.compose.staggeredgrid

import androidx.compose.ui.unit.Dp

data class GridItem(
  val height: Dp, val image: String, val caption: String
)

Define the layout for your Gird items.

Once you have created your data class, you will need to define the layout for your Gird items. This is where you can implement the staggered grid layout. In this example we are using Image on top of it we are showing a caption, Just like feature image.

package com.compose.staggeredgrid

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
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.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage

@Composable
fun GridItem(photoItem: GridItem) {
  Card(
    modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(8.dp), elevation = 4.dp
  ) {
    /**
     *  Create box for display grid item
     */
    Box(
      modifier = Modifier
        .height(photoItem.height)
        .fillMaxWidth()
    ) {
      /**
       *  load image from server
       */
      AsyncImage(
        model = photoItem.image,
        contentDescription = null,
        contentScale = ContentScale.Crop,
        modifier = Modifier
          .fillMaxWidth()
          .fillMaxHeight()
      )
      Box(
        modifier = Modifier
          .fillMaxSize()
          .background(
            Brush.verticalGradient(
              colors = listOf(Color.Transparent, Color.Black),
              startY = 300f,
            )
          )
      ) {
        /**
         *  Text over the image
         */
        Text(
          modifier = Modifier
            .align(alignment = Alignment.BottomStart)
            .padding(8.dp),
          text = photoItem.caption,
          color = Color.White,
          fontSize = 16.sp,
        )
      }
    }
  }
}

Implement the staggered grid layout using Compose

Once you have defined the layout for your gird items, you can implement the staggered grid layout using a LazyVerticalStaggeredGrid in compose. This LazyVerticalStaggeredGrid allows you to create a grid of items where each item can have a different height. Here is an example code snippet

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun StaggeredGridView(items: List<GridItem>) {
  LazyVerticalStaggeredGrid(
    columns = StaggeredGridCells.Adaptive(150.dp),
    modifier = Modifier.fillMaxSize(),
    contentPadding = PaddingValues(4.dp),
    verticalItemSpacing = 4.dp,
    horizontalArrangement = Arrangement.spacedBy(4.dp),
  ) {
    items(items) { item ->
      GridItem(photoItem = item)
    }
  }
}

Finally, call StaggeredGridView compose function in surface view

Finally, In the main activity you can call this composable function, like below

package com.compose.staggeredgrid

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.compose.staggeredgrid.ui.theme.StaggeredGridJetpackComposeTheme
import com.compose.staggeredgrid.utils.getItems

class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      StaggeredGridJetpackComposeTheme {
        // A surface container using the 'background' color from the theme
        /**
         * Prepare grid items list
         */
        val items = getItems()
        /**
         *  Call Staggered GridView Composable Items
         */
        StaggeredGridView(items)
      }
    }
  }
}

Conclusion

All done, that all about staggered grid layout using jetpack compose. I hope this articles will help you, If you have any question please reach out to me in below comment box, I will happy to answer that.

Read our other post on Android Jetpack Compose

Write A Comment