RecyclerView怎么添加分割线?
系统帮我们提供了ItemDecoration抽象类,继承该抽象类重写相应的方法即可。
该类很简单,除去3个已经废弃的方法,只有三个方法,如下:
我们来看以下这三个方法的作用:
/**
* @param outRect Rect to receive the output.
* @param view The child view to decorate
* @param parent RecyclerView this ItemDecoration is decorating
* @param state The current state of RecyclerView.
*/
public void getItemOffsets(
@NonNull Rect outRect,
@NonNull View view,
@NonNull RecyclerView parent,
@NonNull State state) { }
getItemOffset:从名字可以看出,获取item的偏移量,结果保存在第一个参数outRect中(Rect类型是一个矩形,可以设置上,下,左,右四个值,正好对应一个view在四个方向上的偏移量)。
比如我想在每个item的上方空出2个像素的距离,可以这样写:
四个参数依次表示:left,top,right,bottom
outRect.set(0, 2, 0, 0)
/**
* @param c Canvas to draw into
* @param parent RecyclerView this ItemDecoration is drawing into
* @param state The current state of RecyclerView
*/
public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull State state) {}
绘制方法,可以在此方法中绘制你想要的各种效果,这个方法是在绘制itemView之前调用,所以绘制的东西会显示在ItemView的底部。如果有重叠,会被ItemView遮挡。如下图:
绿色区域(重叠部分)被itemView覆盖
/**
* @param c Canvas to draw into
* @param parent RecyclerView this ItemDecoration is drawing into
* @param state The current state of RecyclerView.
*/
public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent,
@NonNull State state) { }
与onDraw相反,此方法在绘制ItemView之后调用,所以绘制的内容在ItemView上层,如果有重叠区域,会覆盖掉ItemView的内容。如下图:
以上方法的调用顺序:
getItemOffset --> onDraw --> 绘制Item --> onDrawOver
Google为我们提供了一个ItemDecoration实现类——DividerItemDecoration(给我们打了个样
如对本文有疑问, 点击进行留言回复!!
Android安卓水滴屏适配状态栏图标(图标过多时显示一个点)
android studio使用Flutter创建web项目
android如何使用taskAffinity属性对任务栈操作控制
android对PDF文件的操作(上传、预览、下载和转存相册)
Android通过代码批量生成字符图标用于给输入法显示状态栏的图标
网友评论