RecyclerView的简单分割线、间距

425 阅读1分钟

分割线


public class MyDecoration extends DividerItemDecoration {
    private int pos = -1;

    / ** * Creates a divider {@ link R ecyclerView.ItemDecoration} that can be used with a * * @ param c ontext     Current context, it will be used to access resources. * @ param o rientation Divider orientation. Should be {@ link #  HORIZONTAL} or {@ link #  VERTICAL}. */  public MyDecoration (Context context, int orientation) {
        super(context, orientation);
    }

//    @Override
//    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
//         pos = parent.getChildLayoutPosition(view);
//        if (pos!=0) {
//            outRect.set(0, 0, 0, getDrawable().getIntrinsicHeight());
//        }
//    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        drawVertical(c, parent);
    }

    private final Rect mBounds = new Rect();

    private void drawVertical(Canvas canvas, RecyclerView parent) {
        canvas.save();
        final int left;
        final int right;
        //noinspection AndroidLintNewApi - NewApi lint fails to handle overrides.
        if (parent.getClipToPadding()) {
            left = parent.getPaddingLeft();
            right = parent.getWidth() - parent.getPaddingRight();
            canvas.clipRect(left, parent.getPaddingTop(), right,
                    parent.getHeight() - parent.getPaddingBottom());
        } else {
            left = 0;
            right = parent.getWidth();
        }

        final int childCount = parent.getChildCount();
        //int i = 1 跳过第一行
        //i < childCount-1 到最后一行
        //i < childCount最后一行的末尾还会加分割线
        for (int i = 1; i < childCount-1; i++) {
            final View child = parent.getChildAt(i);
            parent.getDecoratedBoundsWithMargins(child, mBounds);
            final int bottom = mBounds.bottom + Math.round( child.getTranslationY());
            final int top = bottom - getDrawable().getIntrinsicHeight();
            getDrawable().setBounds(left, top, right, bottom);
            getDrawable().draw(canvas);
        }
        canvas.restore();
    }
}

item间的空白

public class SpaceItemTopDecoration extends RecyclerView.ItemDecoration {
    private int space = 0;

    /**
     * @param space 行间距大小 px
     */
    public SpaceItemTopDecoration(int space) {
        this.space = space;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        if (parent.getChildAdapterPosition(view) != 0) {//第一行除外
            outRect.top = space;
        }
        if (parent.getChildAdapterPosition(view)==parent.getChildCount()-1) {
//            最后一行底部增加距离,展示阴影效果
            outRect.bottom = space;
        }
    }
}