效果图
Step1. 编写activity_main.laylout
首先,在主布局中添加Recyclerview,设置背景色,这个就是分割线的颜色
<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/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff888888"
/>
</LinearLayout>
Step2. item_text.laylout
这里新建了一个简单的TextView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/item_tx"
android:layout_width="match_parent"
android:layout_height="120dp"
android:gravity="center"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
Step3.主活动编写recyclerView.AddItemDecoration方法,重写getItemOffsets方法,outRect.set(0,0,0,3);设置bottom偏移宽度,就是分割线的宽度
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
outRect.set(0,0,0,10);//分割线宽度
}
@Override
public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
super.onDraw(c, parent, state);
Paint paint=new Paint();
paint.setColor(Color.WHITE);//列表TextView的颜色
int count=parent.getChildCount();//获取列表数量
for(int i=0;i<count;i++){
final View child=parent.getChildAt(i);
//最后一个底下不需要分割线
if(i==count-1){
c.drawRect(child.getLeft(), child.getTop(),child.getRight(),
child.getBottom()+10,paint);
}
else {
c.drawRect(child.getLeft(), child.getTop(),child.getRight(),
child.getBottom(),paint);
}
}
}