RecyclerView 到达顶部的条件有很多种,除了Scroll外,很多都要和LayoutManager的具体类型相关。

特别的,但第一个item的height为0的时候,canScrollVertically的判断就会出错。


这里提出一种和具体类型无关的,并能避免height为0时出现错误的方法:

    private static Rect InsertRect = new Rect();    private static boolean canScrollVertically(RecyclerView view, int direction) {        if (direction < 1) {            if (view.getChildCount() > 0) {                // 获取第一个View                View child = view.getChildAt(0);                if (child != null && view.getChildAdapterPosition(child) == 0) {                    // 这个view是否是第0个item                    RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();                    RecyclerView.LayoutManager layoutManager = view.getLayoutManager();                    if (layoutManager != null && layoutParams != null) {                       // 获得ItemDecorations中的偏移                        layoutManager.calculateItemDecorationsForChild(child, InsertRect);                        // 第一个View的top修正偏移和margin后的实际位置                          int top = child.getTop() - InsertRect.top - layoutParams.topMargin;                        return top < 0; // >= 0 到顶                    }                }            }        }        return view.canScrollVertically(direction);    }



原理就是当第一个View是第0项,并且view的top在偏移和margin修正后 >= 0就到达顶端了。


更多相关文章

  1. Android(安卓)7.0以上(包含8.0), popupWindow弹窗位置异常, 解决
  2. android中scrollTo和scrollBy的理解~~
  3. Google TV 2.0:开发者终于获得正式版 SDK 开发工具
  4. Android(安卓)约束布局ConstraintLayout解析
  5. android crash 调试
  6. ConstraintLayout使用笔记
  7. BPF初探 - Android中BPF运用实例
  8. axml格式
  9. Android(安卓)Bitmap 相关操作

随机推荐

  1. Android中ListView动态添加删除项
  2. [Android][UI]模拟器启动界面动画效果的
  3. Android与mqtt双向SSL认证
  4. Android笔试和面试精华题
  5. android中图片的处理(绘制圆形,圆角||缩略
  6. 【Android】在View显示前预估其大小
  7. Android Studio 中Conflict with depende
  8. Android NDK: Are you sure your NDK_MOD
  9. Android(安卓)之 按两次关闭窗口
  10. android去除标题栏和状态栏