How do i get perfect aligning between the gridView items, i have added the gridview using java and it\'s base adapter is set in which i added the image and textview.
Xml
Try this,
recyclerView = (RecyclerView) findViewById(R.id.recyclerView );
recyclerView .setLayoutManager(new GridLayoutManager(getActivity(), 2));
int spanCount = 2;
int spacing_left = 10;
int spacing_top=15;
recyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing_left, spacing_top));
GridSpacingItemDecoration:
/* set spacing for grid view */
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
final private int spanCount, spacing, spacing_top;
final private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing_left, int spacing_top) {
this.spanCount = spanCount;
this.spacing = spacing_left;
this.includeEdge = true;
this.spacing_top = spacing_top;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item phases_position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount;
outRect.right = (column + 1) * spacing / spanCount;
if (position < spanCount) { // top edge
outRect.top = spacing_top;
}
outRect.bottom = spacing_top; // item bottom
} else {
outRect.left = column * spacing / spanCount;
outRect.right = spacing - (column + 1) * spacing / spanCount;
if (position >= spanCount) {
outRect.top = spacing_top; // item top
}
}
}
}