RecyclerView中ItemDecorationd的简单使用(二)---为item设置分割线

ItemDecorationd  为 item 设置底部分割线

效果图(图有点丑,但意思到)

RecyclerView中ItemDecorationd的简单使用(二)---为item设置分割线_第1张图片


同样先设置 MyDeviderDecorationd 继承 ItemDecorationd

public class MyDeviderDecoration extends RecyclerView.ItemDecoration {
        private int mydevider;
        private Paint dividerPaint;

        public MyDeviderDecoration(Context context) {
            dividerPaint = new Paint();
            //设置分割线颜色
            dividerPaint.setColor(context.getResources().getColor(R.color.colorAccent));
            //设置分割线宽度
            mydevider = context.getResources().getDimensionPixelSize(R.dimen.divider_bottom);
        }
    
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.bottom = mydevider;
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            int childCount = parent.getChildCount();
            int left = parent.getPaddingLeft();
            int right = parent.getWidth() - parent.getPaddingRight();

            for (int i = 0; i < childCount - 1; i++) {
                View view = parent.getChildAt(i);
                float top = view.getBottom();
                float bottom = view.getBottom() + mydevider;
                c.drawRect(left, top, right, bottom, dividerPaint);
            }
        }
    }

同样在setAdapter()之前加上如下代码:

 recyclerView.addItemDecoration(new MyDeviderDecoration(this));

完成~





你可能感兴趣的:(项目必备)