Skip to content

Instantly share code, notes, and snippets.

@wching
Forked from hrules6872/SpaceItemDecoration.java
Created February 3, 2016 06:19
Show Gist options
  • Save wching/57d103f661661eceae7d to your computer and use it in GitHub Desktop.
Save wching/57d103f661661eceae7d to your computer and use it in GitHub Desktop.
Space ItemDecoration for RecyclerView
public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
private int space;
private boolean addSpaceFirstItem;
private boolean addSpaceLastItem;
public SpaceItemDecoration(int space) {
this(space, false, false);
}
public SpaceItemDecoration(int space, boolean addSpaceFirstItem, boolean addSpaceLastItem) {
this.space = space;
this.addSpaceFirstItem = addSpaceFirstItem;
this.addSpaceLastItem = addSpaceLastItem;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
if (space <= 0) {
return;
}
if (addSpaceFirstItem && parent.getChildLayoutPosition(view) < 1 || parent.getChildLayoutPosition(view) >= 1) {
if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
outRect.top = space;
} else {
outRect.left = space;
}
}
if (addSpaceLastItem && parent.getChildAdapterPosition(view) == getTotalItemCount(parent) - 1) {
if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
outRect.bottom = space;
} else {
outRect.right = space;
}
}
}
private int getTotalItemCount(RecyclerView parent) {
return parent.getAdapter().getItemCount();
}
private int getOrientation(RecyclerView parent) {
if (parent.getLayoutManager() instanceof LinearLayoutManager) {
return ((LinearLayoutManager) parent.getLayoutManager()).getOrientation();
} else {
throw new IllegalStateException("SpaceItemDecoration can only be used with a LinearLayoutManager.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment