RecyclerView添加虚线分割线

先看下效果图吧

RecyclerView添加虚线分割线

有些同学觉得这不是很简单吗,随便百度一大堆(好吧你赢了,我只是来做笔记的。。。)

简单粗暴上关键代码

mAdapter.setData(data);
mGrideLayout.setAdapter(mAdapter);
mGrideLayout.setLayoutManager(new GridLayoutManager(this, 2));
mGrideLayout.addItemDecoration(new DividerGridItemDecoration(this));

关键这个DividerGridItemDecoration

//绘制水平虚线
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.GRAY);
Path path = new Path();
path.moveTo(left, top);
path.lineTo(right,top);
PathEffect effects = new DashPathEffect(new float[]{8,8,8,8},0); mPaint.setPathEffect(effects);
c.drawPath(path, mPaint);
//绘制垂直虚线 
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.GRAY);
Path path = new Path();
path.moveTo(left, top);
path.lineTo(left,bottom);
PathEffect effects = new DashPathEffect(new float[]{8,8,8,8},0); mPaint.setPathEffect(effects);
c.drawPath(path, mPaint);

好了就这样了?不,我想说我碰到的一些坑,分享给各位同学

问题一:

RecyclerView添加虚线分割线

What?右边怎么多出来了一条线,我想说这个类DividerGridItemDecoration我没动过

好吧上代码:

修改前;

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_gride"
        android:paddingBottom="200dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>
</LinearLayout>

修改后:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_gride"
        android:paddingBottom="200dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>
</LinearLayout>

应该是在父布局的边界才隐藏,在来看看美团的,也是这个细节问题(截图不明显)

RecyclerView添加虚线分割线

问题二:

我现在recyclerview中设置了paddingbottom,然后就。。。估计这就是paint的神奇之处吧

RecyclerView添加虚线分割线

参考:http://blog.csdn.net/lmj623565791/article/details/45059587

            http://www.jianshu.com/p/fe41428ca2f3