不断学习,做更好的自己!💪
视频号CSDN简书欢迎打开微信,关注我的视频号:KevinDev点我点我 简介ItemDecoration
是 RecyclerView
的一个抽象静态内部类,负责装饰 Item
视图,例如添加间距、高亮或者分组边界等。
1. 效果图
2. 源码
public class DividerItemDecoration extends RecyclerView.ItemDecoration{
private Context mContext;
private Drawable mDivider;
private int mOrientation;
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
//我们通过获取系统属性中的listDivider来添加,在系统中的AppTheme中设置
public static final int[] ATRRS = new int[]{
android.R.attr.listDivider
};
public DividerItemDecoration(Context context, int orientation) {
this.mContext = context;
final TypedArray ta = context.obtainStyledAttributes(ATRRS);
this.mDivider = ta.getDrawable(0);
ta.recycle();
setOrientation(orientation);
}
//设置屏幕的方向
public void setOrientation(int orientation){
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST){
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
if (mOrientation == HORIZONTAL_LIST){
drawVerticalLine(c, parent, state);
}else {
drawHorizontalLine(c, parent, state);
}
}
//画横线, 这里的parent其实是显示在屏幕显示的这部分
public void drawHorizontalLine(Canvas c, RecyclerView parent, RecyclerView.State state){
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i
关注
打赏