软件编程
位置:首页>> 软件编程>> Android编程>> Android RecyclerView实现悬浮吸顶、分隔线、到底提示效果

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

作者:MrChen的成长之路  发布时间:2022-02-26 16:59:39 

标签:recyclerview,悬浮吸顶,分隔线,提示

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

一、顶部吸附效果图

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

二、顶部不吸附效果图

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

三、不满一屏效果

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实现悬浮吸顶、分隔线、到底提示效果网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

来源:https://blog.csdn.net/weixin_38062353/article/details/103879834

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com