RecyclerViewItemDivider.java
1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.cnlive.goldenline.util;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* RecyclerViewItem的分割线
* Created by zhangshuai on 2016-04-18.
*/
public class RecyclerViewItemDivider extends RecyclerView.ItemDecoration {
private Drawable mDrawable;
public RecyclerViewItemDivider(@NonNull Context context, int resId) {
//在这里我传入作为Divider的Drawable对象
mDrawable=context.getResources().getDrawable(resId);
}
@Override
public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent) {
//super.onDrawOver(c, parent);
final int left=parent.getPaddingLeft();
final int right=parent.getWidth()- parent.getPaddingRight();
final int childCount=parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
//以下计算主要用来确定绘制的位置
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDrawable.getIntrinsicHeight();
mDrawable.setBounds(left, top, right, bottom);
mDrawable.draw(c);
}
}
@Override
public void getItemOffsets(@NonNull Rect outRect, int position, RecyclerView parent) {
outRect.set(0, 0, 0, mDrawable.getIntrinsicWidth());
}
}