Dimitry Ivanov

Grid items equal spacing (RecyclerView)


This is how to achieve equal spacing between grid elements and RecyclerView borders. Applicable for both GridLayoutManager and StaggeredGridLayoutManager. No modification of existing Adapter is required.

2 columns 3 columns 4 columns

The simple trick is to combine RecyclerView.ItemDecoration and RecyclerView paddings:

// initialise RecyclerView 
final RecyclerView recyclerView = findViewById(R.id.recycler_view);
final GridLayoutManager layoutManager = new GridLayoutManager(this, spanCount);
recyclerView.setAdapter(new Adapter(this));

final int spacing = getResources().getDimensionPixelSize(R.dimen.recycler_spacing) / 2;

// apply spacing
recyclerView.setPadding(spacing, spacing, spacing, spacing);
recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.set(spacing, spacing, spacing, spacing);

In the snippet above we are dividing desired spacing by two. We need this because we are applying half of the spacing to each element and RecyclerView borders. This way all items will be surrounded by equal spacing.

Next > Square Frame Layout