How to avoid double space between items when using RecyclerView with StaggeredGridLayoutManager?

outofmemory picture outofmemory · Mar 7, 2015 · Viewed 9.4k times · Source

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!

Answer

Mark Hetherington picture Mark Hetherington · Aug 24, 2015

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;
    }
}