Skip to content

Instantly share code, notes, and snippets.

@UweTrottmann
Last active December 9, 2023 14:43
Show Gist options
  • Save UweTrottmann/c6344c32aa61d1bec5a6 to your computer and use it in GitHub Desktop.
Save UweTrottmann/c6344c32aa61d1bec5a6 to your computer and use it in GitHub Desktop.
RecyclerView grid spacing decoration for use with GridLayoutManager.
/*
* Copyright 2015 Uwe Trottmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Adds spacing in between items in a grid. Meaning, there will be no margin added at the outer
* edges of the grid.
*/
public class GridInsetDecoration extends RecyclerView.ItemDecoration {
private int insetHorizontal;
private int insetVertical;
public GridInsetDecoration(Context context) {
insetHorizontal = context.getResources()
.getDimensionPixelSize(R.dimen.grid_horizontal_spacing);
insetVertical = context.getResources()
.getDimensionPixelOffset(R.dimen.grid_vertical_spacing);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
RecyclerView.State state) {
GridLayoutManager.LayoutParams layoutParams
= (GridLayoutManager.LayoutParams) view.getLayoutParams();
int position = layoutParams.getViewPosition();
if (position == RecyclerView.NO_POSITION) {
outRect.set(0, 0, 0, 0);
return;
}
// add edge margin only if item edge is not the grid edge
int itemSpanIndex = layoutParams.getSpanIndex();
// is left grid edge?
outRect.left = itemSpanIndex == 0 ? 0 : insetHorizontal;
// is top grid edge?
outRect.top = itemSpanIndex == position ? 0 : insetVertical;
outRect.right = 0;
outRect.bottom = 0;
}
}
@Stuazt
Copy link

Stuazt commented May 30, 2018

I don't think decorations can work as line/column dividers if the RecyclerView has no padding at all.

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