RecyclerView之分割线

前些天利用周末时间捣鼓了一下Recyclerview,其实虽然现在RecyclerView出来了这么久,之所以得到我们的偏爱是因为它的高度解耦和高度可自定义非常灵活。我相信很多人在使用RecyclerView的时候曾经也为分割线头疼过,有人可能使用很简单的方法就是在每一个item里面加一个view设置背景最后在adapter里面处理最后分割线。但是久而久之你会发现你在项目中使用RecyclerView的频率非常高,不停的重写这样的代码难道你不觉得累么?说实话我就是觉得繁琐和重复无用代码所以想造轮子,当初真是很傻很天真啊!好啦,该进入正题了

首先在gradle里面添加依赖如下:

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:design:25.0.0'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.android.support:appcompat-v7:25.0.0'
}

然后在绑定一些简单的数据如图

对于RecyclerView的layoutManager你了解多少?水平、垂直、网格都少不了它,去看看源码你就会发现新大陆的

if (isVertical) {//水平布局
            isVertical = false;
            addItemDecoration = new DividerItemDecoration(MainActivity.this, LinearLayoutManager.HORIZONTAL);
            recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false));
            recyclerView.addItemDecoration(addItemDecoration);
        } else {//竖直布局
            isVertical = true;
            addItemDecoration = new DividerItemDecoration(MainActivity.this, LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
            recyclerView.addItemDecoration(addItemDecoration);
        }
if (isGrid) {//流式布局
            isGrid = false;
            recyclerView.setAdapter(new MyStaggedRecyclerAdapter(infoBeans));
            recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3,LinearLayoutManager.VERTICAL));


        } else {//网格布局
            isGrid = true;
            dividerGridViewItemDecoration = new DividerGridViewItemDecoration(MainActivity.this);
            recyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this,3));
            recyclerView.setAdapter(new MyRecyclerAdapter(infoBeans));
            recyclerView.addItemDecoration(dividerGridViewItemDecoration);
        }
}

这些LayoutManager都是提供不需要自己手动写,下面进入今天主题分割线了。首先,我们可以思考RecyclerView它到底是怎么弄出的分割线呢?
我们进入ItemDecoration就能发现它是RecyclerView的一个抽象内部类还有onDraw方法

/**
         * Draw any appropriate decorations into the Canvas supplied to the RecyclerView.
         * Any content drawn by this method will be drawn before the item views are drawn,
         * and will thus appear underneath the views.
         *
         * @param c Canvas to draw into
         * @param parent RecyclerView this ItemDecoration is drawing into
         * @param state The current state of RecyclerView
         */
        public void onDraw(Canvas c, RecyclerView parent, State state) {
            onDraw(c, parent);
        }

        /**
         * @deprecated
         * Override {@link #onDraw(Canvas, RecyclerView, RecyclerView.State)}
         */
        @Deprecated
        public void onDraw(Canvas c, RecyclerView parent) {
        }
/**
         * @deprecated
         * Use {@link #getItemOffsets(Rect, View, RecyclerView, State)}
         */
        @Deprecated
        public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
            outRect.set(0, 0, 0, 0);
        }

        /**
         * Retrieve any offsets for the given item. Each field of <code>outRect</code> specifies
         * the number of pixels that the item view should be inset by, similar to padding or margin.
         * The default implementation sets the bounds of outRect to 0 and returns.
         *
         * <p>
         * If this ItemDecoration does not affect the positioning of item views, it should set
         * all four fields of <code>outRect</code> (left, top, right, bottom) to zero
         * before returning.
         *
         * <p>
         * If you need to access Adapter for additional data, you can call
         * {@link RecyclerView#getChildAdapterPosition(View)} to get the adapter position of the
         * View.
         *
         * @param outRect Rect to receive the output.
         * @param view    The child view to decorate
         * @param parent  RecyclerView this ItemDecoration is decorating
         * @param state   The current state of RecyclerView.
         */
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
            getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
                    parent);
        }

没错通过RecyclerView代码可以看出来分割线的绘制就是通过这两个方法确定绘制区域和执行绘制的,下面我们来自定义一个DividerItemDecoration继承ItemDecoration重写onDraw和getItemOffsets方法

    @Override
    public void onDraw(Canvas c, RecyclerView parent, State state) {
        //RecyclerView会调用该方法绘制分割线
        if(mOrientation == LinearLayoutManager.VERTICAL){//竖直
            drawVertical(c,parent);
        }else{//水平
            drawHorizontal(c,parent);
        }
        
        super.onDraw(c, parent, state);
    }
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
            State state) {
        // 调用此方法先获取条目之间的宽度并设置outRect矩形区域
        if(mOrientation == LinearLayoutManager.VERTICAL){
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        }else{
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0 );
        }
    }
   private void drawHorizontal(Canvas c, RecyclerView parent) {// 画水平线
        int top = parent.getPaddingTop();
        int bottom = parent.getHeight() - parent.getPaddingBottom();
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount ; i++) {
            View child = parent.getChildAt(i);
            
            LayoutParams params = (LayoutParams) child.getLayoutParams();
            int left = child.getRight() + params.rightMargin + Math.round(ViewCompat.getTranslationX(child));
            int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top , right, bottom);
            mDivider.draw(c);
        }
    }

    private void drawVertical(Canvas c, RecyclerView parent) {// 画水竖直
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount ; i++) {
            View child = parent.getChildAt(i);
            
            LayoutParams params = (LayoutParams) child.getLayoutParams();
            int top = child.getBottom() + params.bottomMargin + Math.round(ViewCompat.getTranslationY(child));
            int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top , right, bottom);
            mDivider.draw(c);
        }
    }

如图我们会发现一个问题,最后一项分割线还是绘制了,那么需要我们自己处理一下


垂直和水平.gif
@Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
            State state) {
        // 调用此方法先获取条目之间的宽度并设置outRect矩形区域
        // 最后一项不需要分割线所以可以设置偏移量都为0
        if (parent.getChildViewHolder(view).getAdapterPosition() == parent.getAdapter().getItemCount() - 1) {
            outRect.set(0, 0, 0, 0);
            return;
        }
        if(mOrientation == LinearLayoutManager.VERTICAL){
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        }else{
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0 );
        }
    }

在getItemOffsets方法中加入判断是不是最后一项即可
那对于gridLayout的话稍微麻烦一点,底部和右边都需要我们自己计算上代码

@Override
    @Deprecated
    public void getItemOffsets(Rect outRect, int itemPosition,
            RecyclerView parent) {
        // 四个方向的偏移值
        int right = mDivider.getIntrinsicWidth();
        int bottom = mDivider.getIntrinsicHeight();
        if (isLastRow(itemPosition,parent)) {//最后一行
            bottom = 0;
        }
        if (isLastColum(itemPosition,parent)) {//最后一列
            right = 0;
        }
        outRect.set(0, 0, right, bottom);
    }

先计算四个方向的偏移量,判断最后一行和最后一列做处理

//最后一行
    public boolean isLastRow(int itemPosition, RecyclerView parent) {
        int spanCount = getSpanCount(parent);
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            int childCount = parent.getAdapter().getItemCount();
            int lastRow = childCount % spanCount;
            //最后一行的数量小于spanCount
            if (lastRow == 0 || lastRow < spanCount) {
                return true;
            }
        }
        return false;
    }
    //最后一列
    public boolean isLastColum(int itemPosition, RecyclerView parent) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            int spanCount = getSpanCount(parent);
            if ((itemPosition + 1) % spanCount == 0) {
                return true;
            }

        }
        return false;
    }

    private int getSpanCount(RecyclerView parent){
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if(layoutManager instanceof GridLayoutManager){
            GridLayoutManager lm = (GridLayoutManager)layoutManager;
            int spanCount = lm.getSpanCount();
            return spanCount;
        }
        return 0;
    }

处理之后效果如下

网格和流式.gif

最后一个是流式布局很简单了,这里就不说了,有兴趣可以自己玩玩,之后其实我也发现一个问题,就是当你的item数很少的时候即使你的recyclerview是全屏,最后一行也会绘制分割线,有解决方案的可以和我分享一下哦!!!

项目链接 https://github.com/389987790/RecyclerViewItemDecoration

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,657评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,889评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,057评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,509评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,562评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,443评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,251评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,129评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,561评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,779评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,902评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,621评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,220评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,838评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,971评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,025评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,843评论 2 354

推荐阅读更多精彩内容