Last active
May 12, 2017 08:01
-
-
Save dcampogiani/f4d8fa40550256e0f82533f84eb4eb17 to your computer and use it in GitHub Desktop.
Simple RecyclerView.ItemDecoration with fluent api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.graphics.Rect; | |
import android.support.v7.widget.RecyclerView; | |
import android.view.View; | |
public class SpacesItemDecoration extends RecyclerView.ItemDecoration { | |
private final int leftSpace; | |
private final int topSpace; | |
private final int rightSpace; | |
private final int bottomSpace; | |
private final boolean skipFirst; | |
private SpacesItemDecoration() { | |
this(0, 0, 0, 0, false); | |
} | |
private SpacesItemDecoration(int leftSpace, int topSpace, int rightSpace, int bottomSpace, boolean skipFirst) { | |
this.leftSpace = leftSpace; | |
this.topSpace = topSpace; | |
this.rightSpace = rightSpace; | |
this.bottomSpace = bottomSpace; | |
this.skipFirst = skipFirst; | |
} | |
private SpacesItemDecoration(Builder builder) { | |
leftSpace = builder.leftSpace; | |
topSpace = builder.topSpace; | |
rightSpace = builder.rightSpace; | |
bottomSpace = builder.bottomSpace; | |
skipFirst = builder.skipFirst; | |
} | |
@Override | |
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { | |
if (!skipFirst || parent.getChildAdapterPosition(view) != 0) { | |
outRect.left = leftSpace; | |
outRect.right = rightSpace; | |
outRect.top = topSpace; | |
outRect.bottom = bottomSpace; | |
} | |
} | |
public static final class Builder { | |
private int leftSpace = 0; | |
private int topSpace = 0; | |
private int rightSpace = 0; | |
private int bottomSpace = 0; | |
private boolean skipFirst = false; | |
public Builder() { | |
} | |
public Builder left(int val) { | |
leftSpace = val; | |
return this; | |
} | |
public Builder top(int val) { | |
topSpace = val; | |
return this; | |
} | |
public Builder right(int val) { | |
rightSpace = val; | |
return this; | |
} | |
public Builder bottom(int val) { | |
bottomSpace = val; | |
return this; | |
} | |
public Builder skipFirst(boolean val) { | |
skipFirst = val; | |
return this; | |
} | |
public Builder vertical(int val) { | |
topSpace = val; | |
bottomSpace = val; | |
return this; | |
} | |
public Builder horizontal(int val) { | |
leftSpace = val; | |
rightSpace = val; | |
return this; | |
} | |
public SpacesItemDecoration build() { | |
return new SpacesItemDecoration(this); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: