RecyclerView添加间隔

2021-01-15  本文已影响0人  duoduo7628

继承RecyclerView.ItemDecoration后,在getItemOffsets()中添加间隔即可

public class CommonSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private int spaceTop;
    private int spaceBottom;
    private int spaceLeft;
    private int spaceRight;
    private boolean isOneNo;

    /**
     * @param spaceLeft
     * @param spaceTop
     * @param spaceRight
     * @param spaceBottom
     * @param isDp        是否是dp
     */
    public CommonSpaceItemDecoration(int spaceLeft, int spaceTop, int spaceRight, int spaceBottom, boolean isDp) {

        if (isDp) {
            spaceLeft = YxpSizeUtils.dp2px(spaceLeft);
            spaceTop = YxpSizeUtils.dp2px(spaceTop);
            spaceRight = YxpSizeUtils.dp2px(spaceRight);
            spaceBottom = YxpSizeUtils.dp2px(spaceBottom);
        }


        this.spaceTop = spaceTop;
        this.spaceBottom = spaceBottom;
        this.spaceLeft = spaceLeft;
        this.spaceRight = spaceRight;

    }

    /**
     * @param spaceLeft
     * @param spaceTop
     * @param spaceRight
     * @param spaceBottom
     * @param isDp        是否是dp
     * @param isOneNo     第一个不偏移
     */
    public CommonSpaceItemDecoration(int spaceLeft, int spaceTop, int spaceRight, int spaceBottom, boolean isDp, boolean isOneNo) {

        if (isDp) {
            spaceLeft = YxpSizeUtils.dp2px(spaceLeft);
            spaceTop = YxpSizeUtils.dp2px(spaceTop);
            spaceRight = YxpSizeUtils.dp2px(spaceRight);
            spaceBottom = YxpSizeUtils.dp2px(spaceBottom);
        }

        this.isOneNo = isOneNo;
        this.spaceTop = spaceTop;
        this.spaceBottom = spaceBottom;
        this.spaceLeft = spaceLeft;
        this.spaceRight = spaceRight;
    }

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


        if (isOneNo) {

            if (parent.getChildAdapterPosition(view) != 0) {

                outRect.left = spaceLeft;
                outRect.right = spaceRight;
                outRect.bottom = spaceBottom;
                outRect.top = spaceTop;
            }
        } else {

            outRect.left = spaceLeft;
            outRect.right = spaceRight;
            outRect.bottom = spaceBottom;
            outRect.top = spaceTop;

        }

    }
}

上一篇 下一篇

猜你喜欢

热点阅读