直接上代码
/**
* ListView样式的分割线
*/
public class LinearLayoutItemDecoration extends RecyclerView.ItemDecoration{
private Drawable mDivide;
public LinearLayoutItemDecoration(Context context,int drawableResourceId){
// 获取 Drawable
mDivide = ContextCompat.getDrawable(context,drawableResourceId);
}
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
//在头部添加一个 10px 的空间 除了第一个
int position = parent.getChildAdapterPosition(view);
if(position !=0 ){
outRect.top = mDivide.getIntrinsicHeight();
}
}
/**
* 绘制分割线
* @param c
* @param parent
* @param state
*/
@Override
public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
int childCount = parent.getChildCount();
Rect rect = new Rect();
rect.left = parent.getPaddingLeft();
rect.right = parent.getWidth() - parent.getPaddingRight();
for(int i=1;i<childCount;i++){
//分割线的底部 是item的头部
rect.bottom = parent.getChildAt(i).getTop();
rect.top = rect.bottom - 10;
mDivide.setBounds(rect);
mDivide.draw(c);
}
}
}
网友评论