温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android中如何使用RecyclerView实现悬浮吸顶、分隔线、到底提示效果

发布时间:2021-09-27 15:13:53 来源:亿速云 阅读:186 作者:小新 栏目:编程语言

小编给大家分享一下Android中如何使用RecyclerView实现悬浮吸顶、分隔线、到底提示效果,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

核心实现点

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实现悬浮吸顶、分隔线、到底提示效果”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI