RecyclerView 到达顶部的另一种方式
16lz
2021-01-26
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就到达顶端了。
更多相关文章
- Android(安卓)7.0以上(包含8.0), popupWindow弹窗位置异常, 解决
- android中scrollTo和scrollBy的理解~~
- Google TV 2.0:开发者终于获得正式版 SDK 开发工具
- Android(安卓)约束布局ConstraintLayout解析
- android crash 调试
- ConstraintLayout使用笔记
- BPF初探 - Android中BPF运用实例
- axml格式
- Android(安卓)Bitmap 相关操作