美文网首页
RecyclerView-->分割线

RecyclerView-->分割线

作者: 谢尔顿 | 来源:发表于2018-10-11 16:19 被阅读23次

    使用RecyclerView,添加分割线的方式有以下两种:

    • 在item布局中添加;
    • 使用RecyclerView的addItemDecoration(ItemDecoration fromHtml)方法,我们需要自定义ItemDecoration。

    第一种就不说了,我们直接看第二种的实现。
    自定义一个继承自ItemDecoraton的类,如下:

    public class RvItemDecoration extends RecyclerView.ItemDecoration {
    
        private final Paint mPaint;
    
        public RvItemDecoration(int color){
            mPaint = new Paint();
            mPaint.setColor(color);
            mPaint.setAntiAlias(true);
        }
        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            int childCount = parent.getChildCount();
            //获取需要绘制的区域
            Rect rect = new Rect();
            rect.left = parent.getPaddingLeft();
            rect.right = parent.getWidth() - parent.getPaddingRight();
            for (int i = 0; i < childCount; i++) {
                View childView = parent.getChildAt(i);
                rect.top = childView.getBottom();
                rect.bottom = rect.top + 20;
                c.drawRect(rect,mPaint);
            }
        }
    
        /**
         * 确定分割线的高度或者说是画在什么位置
         * @param outRect
         * @param view
         * @param parent
         * @param state
         */
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            //在每个子view的下面留出20px来画分割线
            outRect.bottom +=20;
        }
    }
    

    对应的效果图:


    我们也可以使用系统默认的分割线DividerItemDecoration,

    mRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    

    也可以利用Drawable

            DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);
            dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.line));
            mRecyclerView.addItemDecoration(dividerItemDecoration);
    

    相关文章

      网友评论

          本文标题:RecyclerView-->分割线

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