Created
May 2, 2018 13:25
-
-
Save iamnaran/3596a1d4c3ebd31f8aefb81f51dd6e26 to your computer and use it in GitHub Desktop.
Space Between RecyclerView. Sticky to edge for 0 and 1 position of recycler view
This file contains hidden or 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; | |
/** | |
* Created by NaRan on 02,May,2018. | |
* Copyright (c) inGrails Pvt. Ltd. All rights reserved. | |
* [email protected] | |
**/ | |
public class SpacingBetweenRecyclerView extends RecyclerView.ItemDecoration { | |
private int spanCount; | |
private int spacing; | |
private boolean includeEdge; | |
private int headerNum; | |
public SpacingBetweenRecyclerView(int spanCount, int spacing, boolean includeEdge, int headerNum) { | |
this.spanCount = spanCount; | |
this.spacing = spacing; | |
this.includeEdge = includeEdge; | |
this.headerNum = headerNum; | |
} | |
@Override | |
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { | |
int position = parent.getChildAdapterPosition(view) - headerNum; // item position | |
if (position >= 0) { | |
int column = position % spanCount; // item column | |
if (includeEdge) { | |
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing) | |
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing) | |
if (position < spanCount) { // top edge | |
outRect.top = spacing; | |
} | |
outRect.bottom = spacing; // item bottom | |
} else { | |
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing) | |
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing) | |
if (position >= spanCount) { | |
outRect.top = spacing; // item top | |
} | |
} | |
} else { | |
/** | |
* adapter position you want to sticky to edge {MATCH_PARENT} | |
* here we are setting 0 and 1 index of recycler view | |
**/ | |
if (parent.getChildAdapterPosition(view) == 0 || parent.getChildAdapterPosition(view) == 1) { | |
outRect.left = 0; | |
outRect.right = 0; | |
outRect.top = 0; | |
outRect.bottom = 0; | |
} else { | |
outRect.left = 16; | |
outRect.right = 16; | |
outRect.top = 16; | |
outRect.bottom = 16; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Call it as:
recyclerView.addItemDecoration(new EqualSpacingItemDecoration(2,16,true,22));