Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Equal column spacing for Android RecyclerView GridLayoutManager by using custom ItemDecoration


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);


In your source code, add ItemOffsetDecoration to your recyclerview.
Item offset value should be half size of the actual value you want to add as space between items.

mRecyclerView.setLayoutManager(new GridLayoutManager(context, NUM_COLUMNS);
ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(context, R.dimen.item_offset);

Also, set item offset value as padding for its recyclerview, and specify android:clipToPadding=false.


DONE. You will get an equal spaces around items.

Thanks, works like a charm !

Thanks, I need some help on other problem.
I want to make items equally spaced in a RecyclerView. Items are not displayed in Grid but are displayed Linearly.
Suppose screen can hold 5 items. Now if list contains less than 5 items then they should take up the whole screen by equally increasing space between them. And if no of items are greater than 5 then user can scroll and the minimum space is maintained between 2 items.
How can I achieve this.

krishnameena commented Jul 5, 2016 edited

It is working fine but I am calling new Activity from the recyclerview and when I am coming back to my previous activity the space automatically becomes 2 times every time. Any solution for that ?

tiwiz commented Aug 17, 2016

@krishnameena: have you tried calling RecyclerView.removeItemDecoration() in the onStop method? :-)

@tiwiz You just saved me loads of fruitless searching. Thank you very much!

Thanks! I spent whole day trying to find a solution.

him407 commented Dec 30, 2016

Thank you, it is work for my apps.

This is amazing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment