简体   繁体   中英

RecyclerView - ItemDecorator - Spacing that does NOT cut off items

I use following divider for vertical linear layout, it works perfetly fine:

public class VerticalSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private final int mVerticalSpaceHeight;

    public VerticalSpaceItemDecoration(int mVerticalSpaceHeight) {
        this.mVerticalSpaceHeight = mVerticalSpaceHeight;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        if (parent.getChildAdapterPosition(view) != parent.getAdapter().getItemCount() - 1)
            outRect.bottom = mVerticalSpaceHeight;
    }
}

Based on this, I tried to write the same decorator for a GridLayout , but the problem is, that it's cutting off my items. It looks like following:

public class GridSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private final int mSpaceSize;
    private final int mCols;

    public GridSpaceItemDecoration(int spaceSize, int cols) {
        this.mSpaceSize = spaceSize;
        mCols = cols;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

        int rows = (int)Math.floor(parent.getAdapter().getItemCount() / mCols) + 1;
        int pos = parent.getChildAdapterPosition(view);
        int col = pos % mCols;
        int row = (int)Math.floor(pos / mCols);

        final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();

        if (col < mCols - 1)
            outRect.right = /*params.rightMargin + view.getPaddingRight() +*/ mSpaceSize;
        if (row < rows - 1)
            outRect.bottom = /*params.leftMargin + view.getPaddingLeft() +*/ mSpaceSize;
    }
}

The result for the two Decorators are following (colors for debugging added):

在此处输入图片说明

The image shows, that in the GridLayout the items are cut off (easily seen at the text underneath the items). I should mention, that the adapters are the same for both, I just use another LayoutManager . The items are of a FIXED SIZE and that is something I need!

RecyclerView上调用setClipChildren(false) ,它应该修复您看到的裁剪,该裁剪是由装饰器创建的间距引起的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM