美文网首页
RecyclerView添加间隔

RecyclerView添加间隔

作者: duoduo7628 | 来源:发表于2021-01-15 09:38 被阅读0次

继承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;

        }

    }
}

相关文章

网友评论

      本文标题:RecyclerView添加间隔

      本文链接:https://www.haomeiwen.com/subject/kjvvaktx.html