ItemOffsetDecoration for GridLayoutManager in RecyclerView
suggest changeThe following example puts an equal offset around items in a grid. The right offset is applied to every column except the first, using the layout manager’s span count. mActivity is not declared in the usage snippet; getActivity() means that snippet is in a Fragment.
ItemOffsetDecoration.java
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);
int position = parent.getChildLayoutPosition(view);
GridLayoutManager manager = (GridLayoutManager) parent.getLayoutManager();
if (position < manager.getSpanCount())
outRect.top = mItemOffset;
if (position % manager.getSpanCount() != 0) {
outRect.right = mItemOffset;
}
outRect.left = mItemOffset;
outRect.bottom = mItemOffset;
}
}
You can add the decoration like this:
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
GridLayoutManager lLayout = new GridLayoutManager(getActivity(), 2);
ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(mActivity, R.dimen.item_offset);
recyclerView.addItemDecoration(itemDecoration);
recyclerView.setLayoutManager(lLayout);
and example item offset
<dimen name="item_offset">5dp</dimen>
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents