这篇文章主要介绍了Android RecyclerView实现悬浮吸顶、分隔线、到底提示效果,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
本文中所有效果通过ItemDecoration实现,通过此实现的可以与业务解耦,让RecyclerView的模板更加简洁,不关心任何辅助性ui,github地址
一、顶部吸附效果图
二、顶部不吸附效果图
三、不满一屏效果
四、核心实现点
1、为什么通过ItemDecoration能够实现,原理?
①通过getItemOffsets()方法获取当前模板view的left、top、right、bottom边距,这些留出的间距用于绘制这些辅助性ui。
// RecyclerView的measure child方法
public void measureChild(@NonNull View child, int widthUsed, int heightUsed) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
//将getItemOffsets()获取的值累加到测量值之中
final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
widthUsed += insets.left + insets.right;
heightUsed += insets.top + insets.bottom;
final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(),
getPaddingLeft() + getPaddingRight() + widthUsed, lp.width,
canScrollHorizontally());
final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(),
getPaddingTop() + getPaddingBottom() + heightUsed, lp.height,
canScrollVertically());
if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) {
child.measure(widthSpec, heightSpec);
}
}
②通过onDrawOver()绘制悬浮视图,绘制的ui在所有子视图之上。
@Override
public void draw(Canvas c) {
super.draw(c);
//在RecyclerView绘制完之后回调onDrawOver()方法
final int count = mItemDecorations.size();
for (int i = 0; i < count; i++) {
mItemDecorations.get(i).onDrawOver(c, this, mState);
}
}
③通过onDraw()方法绘制分割线等视图。
public void onDraw(Canvas c) {
super.onDraw(c);
//先回调onDraw()方法,在绘制RecyclerView子view
final int count = mItemDecorations.size();
for (int i = 0; i < count; i++) {
mItemDecorations.get(i).onDraw(c, this, mState);
}
}
2、“到底提示” 的绘制
由于在getItemOffsets()获取不到子视图的宽高,此时还没有measure,在getItemOffsets()添加高度后,如果不满一屏需要在onDraw()方法中进行修正,修正方式为:
反射修改mDecorInsets属性,重置在getItemOffsets()方法中设置的值。
private void setDecorInsetsBottom(RecyclerView.LayoutParams param, int bottom) {
try {
// 找到RecyclerView.LayoutParams中的mDecorInsets属性值
Field filed = RecyclerView.LayoutParams.class.getDeclaredField("mDecorInsets");
filed.setAccessible(true);
Rect decorRect = (Rect) filed.get(param);
decorRect.bottom = bottom;
} catch (Exception e) {
}
}
总结
以上所述是小编给大家介绍的Android RecyclerView实现悬浮吸顶、分隔线、到底提示效果,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程学习网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
本文标题为:Android RecyclerView实现悬浮吸顶、分隔线、到底提示效果
- 作为iOS开发,这道面试题你能答出来,说明你基础很OK! 2023-09-14
- Android实现监听音量的变化 2023-03-30
- iOS 对当前webView进行截屏的方法 2023-03-01
- SurfaceView播放视频发送弹幕并实现滚动歌词 2023-01-02
- Flutter实现底部和顶部导航栏 2022-08-31
- 详解flutter engine 那些没被释放的东西 2022-12-04
- Android studio实现动态背景页面 2023-05-23
- Android MaterialButton使用实例详解(告别shape、selector) 2023-06-16
- Android实现轮询的三种方式 2023-02-17
- 最好用的ios数据恢复软件:PhoneRescue for Mac 2023-09-14
