You are currently viewing Set spacing in RecyclerView items by custom Item Decorator in Phimpme Android App
Spacing in RecyclerView GridLayoutManager

Set spacing in RecyclerView items by custom Item Decorator in Phimpme Android App

We have decided to shift our images Gallery code from GridView to using Grid Layout manager in RecyclerView in Phimpme Android application. RecyclerView has many advantages as compare to Grid/ List view.

  • Advantages of using layout manager either List, Grid or Staggered.
  • We can use many built in animations.
  • Item decorator for customizing the item.
  • Recycle items using the View Holder pattern

Recycler View documentation

Adding recyclerview in xml






Setting layout manager

mLayoutManager = new GridLayoutManager(this, 3);


In phimpme we have an item as an ImageView, to show into the grid. Setup the Grid using layout manager as above.

Gallery of images is set but there is no spacing in between grid items. Padding will not help in this case.

Found a way to set offset by creating a Custom item decoration class. Add a constructor with parameter as a dimension resource.


public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {

   private int mItemOffset;

   public ItemOffsetDecoration(int itemOffset) {

       mItemOffset = itemOffset;


   public ItemOffsetDecoration(@NonNull Context context, @DimenRes int itemOffsetId) {




   public void getItemOffsets(Rect outRect, View view, RecyclerView parent,

           RecyclerView.State state) {

       super.getItemOffsets(outRect, view, parent, state);

       outRect.set(mItemOffset, mItemOffset, mItemOffset, mItemOffset);





ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(context, R.dimen.item_offset);


Pass the item_offset value in the function. Go through the material design guidelines for a clear understanding of dimensions in item offset.

Pawan Pal

Android Developer. Open Source Enthusiast.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.