Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
RecyclerView as Staggered Grid in Android With Example
Next article icon

RecyclerView as Staggered Grid in Android With Example

Last Updated : 16 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

GridView: A ViewGroup that shows the items in a two-dimensional scrolling grid. In Grid View, each grid is of the same size. i.e., the height and width of each grid are equal. It shows symmetric items in the views. 

Grid view

Staggered GridView: This ViewGroup is the extension of Grid View. In this view, the Grid is of varying size .i.e., their height and width may vary. It shows asymmetric items in the views. It automatically sets the item views according to its height and width.

Staggered GridView

In order to use RecyclerView for creating staggering grid views, we need to use StaggeredGridLayoutManager. LayoutManager is responsible for measuring and positioning item views in the RecyclerView and also recycle the item views when they are no longer visible to the user. There are three types of built-in layout managers.

  1. LinearLayoutManager: It is used to show item views in a vertical and horizontal list.
  2. GridLayoutManager: It is used to show item views grid views.
  3. StaggeredLayoutManager: It is used to show item views in staggered views.

We can also create a custom layout manager by RecyclerView.LayoutManager class.

StaggeredGridLayoutManager(int spanCount, int orientation) 

  • Creates staggered grid layout with given parameters
  • The first parameter, spanCount is used to set the number of columns in a vertical orientation or the number of rows in the horizontal orientation
  • The second parameter, orientation is used to set the vertical or horizontal orientation

Staggered Grid with Vertical Orientation

RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerView);

// staggeredGridLayoutManager with 3 columns and vertical orientation
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL);

// setting recycler view layout to staggered grid
recyclerView.setLayoutManager(staggeredGridLayoutManager);
 

Staggered Grid with Horizontal Orientation

RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerView);

// staggeredGridLayoutManager with 3 rows and horizontal orientation
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.HORIZONTAL);

// setting recycler view layout to staggered grid
recyclerView.setLayoutManager(staggeredGridLayoutManager);
 

Example

In this example, we would store data into ArrayList which is used for populating RecyclerView. After that we set the layout manager of RecyclerView as a staggered grid view and then, we set the Adapter for RecyclerView to show item views. A sample GIF is given below to get an idea about what we are going to do in this article.

Note that we are going to implement this project using the Java language. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Adding dependencies

We are going to use the RecyclerView. So, we need to add the dependency of it. For adding the dependency Go to Gradle Scripts > build.gradle(Module: app) and add the following dependencies. After adding these dependencies you need to click on Sync Now.

dependencies {
  implementation 'androidx.recyclerview:recyclerview:1.1.0'
}

Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. 

XML
<resources>       <color name="colorPrimary">#0F9D58</color>       <color name="colorPrimaryDark">#16E37F</color>       <color name="colorAccent">#03DAC5</color>   </resources> 


Step 3: Working with the activity_main.xml file

In this step, we will create a RecyclerView layout in the activity_main.xml file. Go to app > res > layout > activity_main.xml and add the following code snippet. 

XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <androidx.recyclerview.widget.RecyclerView         android:id="@+id/recyclerView"         android:layout_width="match_parent"         android:layout_height="match_parent" /> </RelativeLayout> 


Step 4: Create a new layout file list_item.xml for the list items of RecyclerView

Go to the app > res > layout > right-click > New > Layout Resource File and name it as list_item. list_item.xml layout file contains an ImageView which is used for populating the rows of RecyclerView.

XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:layout_margin="4dp">      <!--For image src we have used ic_launcher         it is used only for reference how it will look"-->     <ImageView         android:id="@+id/imageView"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:scaleType="fitXY"         android:src="@mipmap/ic_launcher" />      </RelativeLayout> 


Step 5: Creating Adapter class for RecyclerView

Now, we will create an Adapter.java class that will extend the RecyclerView.Adapter with ViewHolder. Go to the app > java > package > right-click and create a new java class and name it as Adapter. In Adapter class we will override the onCreateViewHolder() method which will inflate the list_item.xml layout and pass it to View Holder. Then onBindViewHolder() method where we set data to the Views with the help of View Holder. Below is the code snippet for Adapter.java class.

Java
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList;  // Extends the Adapter class to RecyclerView.Adapter // and implement the unimplemented methods public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {     ArrayList images;     Context context;      // Constructor for initialization     public Adapter(Context context, ArrayList images) {         this.context = context;         this.images = images;     }      @NonNull     @Override     public Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {         // Inflating the Layout(Instantiates list_item.xml layout file into View object)         View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);          // Passing view to ViewHolder         Adapter.ViewHolder viewHolder = new Adapter.ViewHolder(view);         return viewHolder;     }      // Binding data to the into specified position     @Override     public void onBindViewHolder(@NonNull Adapter.ViewHolder holder, int position) {         // TypeCast Object to int type         int res = (int) images.get(position);         holder.images.setImageResource(res);     }      @Override     public int getItemCount() {         // Returns number of items currently available in Adapter         return images.size();     }      // Initializing the Views     public class ViewHolder extends RecyclerView.ViewHolder {         ImageView images;          public ViewHolder(View view) {             super(view);             images = (ImageView) view.findViewById(R.id.imageView);         }     } } 


Step 6: Working with the MainActivity.java file

In MainActivity.java class we create an ArrayList for storing images. These images are placed in the drawable folder(app > res > drawable). You can use any images in place of these. And then we get the reference RecyclerView and set the LayoutManager as StaggeredGridLayoutManager and Adapter, to show items in RecyclerView. Below is the code for the MainActivity.java file.

Java
import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import java.util.ArrayList; import java.util.Arrays;  public class MainActivity extends AppCompatActivity {          RecyclerView recyclerView;      // Using ArrayList to store images data     ArrayList images = new ArrayList<>(Arrays.asList(R.drawable.img_1, R.drawable.img_2, R.drawable.img_3,             R.drawable.img_4, R.drawable.img_5, R.drawable.img_6, R.drawable.img_7, R.drawable.img_8,             R.drawable.img_9, R.drawable.img_10));      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // Getting reference of recyclerView         recyclerView = (RecyclerView) findViewById(R.id.recyclerView);          // Setting the layout as Staggered Grid for vertical orientation         StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL);         recyclerView.setLayoutManager(staggeredGridLayoutManager);          // Sending reference and data to Adapter         Adapter adapter = new Adapter(MainActivity.this, images);          // Setting Adapter to RecyclerView         recyclerView.setAdapter(adapter);     } } 

Output: Run on Emulator


Next Article
RecyclerView as Staggered Grid in Android With Example

A

ankur035
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Android
  • Technical Scripter 2020
Practice Tags :
  • Java

Similar Reads

    Android - RecyclerView as Staggered Grid with Kotlin
    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 Layout Manager to our Recycler View in Android. Note: If y
    5 min read
    Staggered GridView in Android with Example
    StaggeredGridLayout is a LayoutManager in the Android studio similar to GridView, but in StaggeredGridLayout each grid has its own height and width.Difference Between GridView and Staggered GridViewStaggeredGridlayoutThe children are in a staggered grid format.It supports horizontal and vertical lay
    4 min read
    RecyclerView in Android with Example
    RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be custo
    7 min read
    CardView using RecyclerView in Android with Example
    RecyclerView is an extended version of ListView and GridView. It works on the ViewHolder design pattern. With the help of RecyclerView, we can add many extra features to our list of data. Before starting our example on the implementation of CardView in RecyclerView. We should know what CardView and
    9 min read
    RecyclerView using GridLayoutManager in Android With Example
    RecyclerView is the improved version of a ListView in Android. It was first introduced in Marshmallow. Recycler view in Android is the class that extends ViewGroup and implements Scrolling Interface. It can be used either in the form of ListView or in the form of Grid View. How to use RecyclerView a
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences