GridView is a ViewGroup displaying items in a two-dimensional scrolling grid where each grid has the same size. This results in symmetric item views.
Staggered GridView is an extension of the GridView, featuring grids of varying sizes, making the height and width of each grid different. This leads to asymmetric item views.
When creating staggered grid views using RecyclerView, the StaggeredGridLayoutManager is essential. This layout manager is responsible for measuring, positioning item views in the RecyclerView, and recycling item views when they are not visible to the user.
We can create a custom layout manager by extending the RecyclerView.LayoutManager class.
When setting up a staggered grid with a vertical orientation:
RecyclerView
object: RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
StaggeredGridLayoutManager
instance with 3 columns in a vertical orientation: StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL);
RecyclerView
to the staggered grid: recyclerView.setLayoutManager(staggeredGridLayoutManager);
For a staggered grid with a horizontal orientation:
StaggeredGridLayoutManager
with 3 rows in a horizontal orientation: StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.HORIZONTAL);
RecyclerView
: recyclerView.setLayoutManager(staggeredGridLayoutManager);
In this demonstration, data is stored in an ArrayList
to populate the RecyclerView
. The layout manager is set to display a staggered grid view, and the Adapter
for the RecyclerView
is configured to showcase item views. Below is a sample GIF illustrating the project implemented using Java:
Color Name | Color Code |
---|---|
colorPrimary | #0F9D58 |
colorPrimaryDark | #16E37F |
colorAccent | #03DAC5 |
The MainActivity.java class initializes the RecyclerView, sets the layout as Staggered Grid, and assigns an Adapter to display items.
import android.os.Bundle; | import androidx.appcompat.app.AppCompatActivity; |
import androidx.recyclerview.widget.LinearLayoutManager; | import androidx.recyclerview.widget.StaggeredGridLayoutManager; |
import java.util.ArrayList; | import java.util.Arrays; |