Answers above have clarified ways to set margin handling GridLayoutManager and LinearLayoutManager.
But for StaggeredGridLayoutManager, Pirdad Sakhizada's answer says: "It might not work very well with StaggeredGridLayoutManager". It should be the problem about IndexOfSpan.
You can get it by this way:
private static class MyItemDecoration extends RecyclerView.ItemDecoration {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int index = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
}
}