Created
June 13, 2018 12:56
-
-
Save abhimuktheeswarar/958ded39e78c6a9b748106c3b98ccaa0 to your computer and use it in GitHub Desktop.
RecyclerView's ItemDecorator to achieve equal spacing around the items when using a GridLayoutManager
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.GridLayoutManager; | |
import android.support.v7.widget.RecyclerView; | |
import android.view.View; | |
public class EqualSpacingGridItemDecorator extends RecyclerView.ItemDecoration { | |
private final int padding; | |
public EqualSpacingGridItemDecorator(int padding) { | |
this.padding = padding; | |
} | |
@Override | |
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { | |
GridLayoutManager.LayoutParams layoutParams = (GridLayoutManager.LayoutParams) view.getLayoutParams(); | |
GridLayoutManager gridLayoutManager = (GridLayoutManager) parent.getLayoutManager(); | |
float spanSize = layoutParams.getSpanSize(); | |
float totalSpanSize = gridLayoutManager.getSpanCount(); | |
float n = totalSpanSize / spanSize; // num columns | |
float c = layoutParams.getSpanIndex() / spanSize; // column index | |
float leftPadding = padding * ((n - c) / n); | |
float rightPadding = padding * ((c + 1) / n); | |
int position = parent.getChildAdapterPosition(view); | |
//Add top padding only to first row | |
if (position == 0 || position == 1) outRect.top = padding; | |
outRect.left = (int) leftPadding; | |
outRect.right = (int) rightPadding; | |
outRect.bottom = padding; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment