I'm using RecyclerView with StaggeredGridLayoutManager to make a two-column list. But how to set a right margin between left column and right column. I have used this code to make right margin from top, but how to solve double space between to columns.
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = space;
outRect.right = space;
outRect.bottom = space;
// Add top margin only for the first or second item to avoid double space between items
// Add top margin only for the first or second item to avoid double space between items
if((parent.getChildCount() > 0 && parent.getChildPosition(view) == 0)
|| (parent.getChildCount() > 1 && parent.getChildPosition(view) == 1))
outRect.top = space;
}
And in Activity:
recyclerView.addItemDecoration(new SpacesItemDecoration(20));
I've tried to use view.getX()
, it always return 0.
Can anyone help me? Many thanks!
In your source code, add ItemOffsetDecoration to your recyclerview. Item offset value should be half size of the actual value you want to add as space between items. mRecyclerView. setLayoutManager(new GridLayoutManager(context, NUM_COLUMNS); ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(context, R.
The best way is to add the ItemDecoration to the RecyclerView as it affects the individual items and you can have more control over them. The above class extends ItemDecoration and overrides getItemOffsets where the left, right, bottom margins are set based on the constructor injected margins.
A LayoutManager that lays out children in a staggered grid formation. It supports horizontal &vertical layout as well as an ability to layout children in reverse. Staggered grids are likely to have gaps at the edges of the layout.
The following code will handle StaggeredGridLayoutManager, GridLayoutManager, and LinearLayoutManager.
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int halfSpace;
public SpacesItemDecoration(int space) {
this.halfSpace = space / 2;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getPaddingLeft() != halfSpace) {
parent.setPadding(halfSpace, halfSpace, halfSpace, halfSpace);
parent.setClipToPadding(false);
}
outRect.top = halfSpace;
outRect.bottom = halfSpace;
outRect.left = halfSpace;
outRect.right = halfSpace;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With