RecyclerView 到达顶部的另一种方式

来源:互联网 发布:淘宝千色药妆是正品么 编辑:程序博客网 时间:2024/05/16 14:36

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就到达顶端了。


原创粉丝点击