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 GridView
- The children’s are in a staggered grid format.
- It supports horizontal and vertical layout
- Example: Pinterest, a wallpaper app, status app, etc
- The children’s in a rectangular grid format
- It also supports horizontal and vertical layout
- Example: Flipkart, Amazon, wallpaper app, etc
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: Creating 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 choose Java as the language though we are going to implement this project in Java language.
Step 2: Before going to the coding section first do some pre-task
Go to Gradle Scripts > build.gradle (Module: app) section and import following dependencies and click the “sync Now” on the above pop up.
// Adding Recycler view
Step 3: Designing the UI
In the activity_main.xml file add a RecyclerView as shown below.
Now we create a new layout resource file ( recyclerview_row.xml ) inside it we add a simple ImageView and set it android:scaleType=”fitXY” complete code of recyclerview_row.xml is shown below
Step 4: Coding Part
First, we create a RecyclerViewAdapter.java class and extend it to RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> and implements its methods as shown below. Below is the code for the RecyclerViewAdapter.java file. Comments are added inside the code to understand the code in more detail.
Now Open the MainActivity.java file there within the class, first of all, create the object of the RecyclerViewAdapter, RecyclerView class, and an ArrayList to store ids of images
// creating recyclerviewadapter object
// creating arrayList
// creating recycler view object
Now inside the onCreate() method, link those objects with their respective IDs that are given in the activity_main.xml file.
// adding values to arrayList
ImageList = new ArrayList<>(Arrays.asList(
recyclerView = findViewById(R.id.recycleViewStagged);
Now inside onCreate() method, we create a RecyclerView.LayoutManager (Learn more about StaggeredGridLayoutManager) and set it to RecyclerView
// setting recyclerView layoutManager
RecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
Now we initialize and setAdapter()
recyclerViewAdapter = new RecyclerViewAdapter(this, ImageList);
// setting recycle view adapter
Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.