前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android RecyclerView实现悬浮吸顶、分隔线、到底提示效果

Android RecyclerView实现悬浮吸顶、分隔线、到底提示效果

作者头像
砸漏
发布2020-10-16 12:15:22
1.9K0
发布2020-10-16 12:15:22
举报
文章被收录于专栏:恩蓝脚本

本文中所有效果通过ItemDecoration实现,通过此实现的可以与业务解耦,让RecyclerView的模板更加简洁,不关心任何辅助性ui,github地址

一、顶部吸附效果图

所有都吸附
所有都吸附

二、顶部不吸附效果图

顶部不吸附效果
顶部不吸附效果

三、不满一屏效果

不满一屏效果
不满一屏效果

四、核心实现点

1、为什么通过ItemDecoration能够实现,原理?

①通过getItemOffsets()方法获取当前模板view的left、top、right、bottom边距,这些留出的间距用于绘制这些辅助性ui。

代码语言:javascript
复制
// 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在所有子视图之上。

代码语言:javascript
复制
@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()方法绘制分割线等视图。

代码语言:javascript
复制
 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()方法中设置的值。

代码语言:javascript
复制
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实现悬浮吸顶、分隔线、到底提示效果,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对ZaLou.Cn网站的支持! 如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档