Equal Space Between Recyclerview Grid Layout Columns Android




ItemOffsetDecoration

public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {

    private int mItemOffset;

    public ItemOffsetDecoration(int itemOffset) {
        mItemOffset = itemOffset;
    }

    public ItemOffsetDecoration(@NonNull Context context, @DimenRes int itemOffsetId) {
        this(context.getResources().getDimensionPixelSize(itemOffsetId));
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
            RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.set(mItemOffset, mItemOffset, mItemOffset, mItemOffset);
    }
}

implementation

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);
mRecyclerView.addItemDecoration(itemDecoration);
Also, set item offset value as padding for its recyclerview, and specify android:clipToPadding=false.
<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerview_grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:padding="@dimen/item_offset"/>
Share on Google Plus

About Mayank Sharma

Mayadi is a knowlage source. You can learn, explore and play many things in a proper way. Mayadi Provides Best, Perfect and Quality Information. subscribe our youtube channel to be updated and and don't forget to take a look on our blog within every week, because we are here to upgrade your knowladge. We love to see you again and again and again...
    Blogger Comment
    Facebook Comment

6 comments:

  1. Glad to hear that it helped you, btw we moved to our new website http://www.androidbreakdown.com/
    have a look and also subscribe to our channel.
    https://www.youtube.com/mayadi

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. A quick help for resolving the issue... :)

    ReplyDelete
  4. Perfect Answer.

    ReplyDelete