关于recycleview获取滑动距离,官方的api 调用得到的是0。有大神有更简单直接的方法获取,欢迎告知。
网上的方法都是千篇一律,有趣的很少。并不好用。
于是乎,
笔者就想只能自己 动手 看能不能做记录,开始的思路是这样的,保存每个条目的之前所有条目的总高度之和,然后取出用总高度之和 减去第一个 显示条目的gettop()获取到滑动距离。经过本人测试,正常速度滑动还可以,但是飞速滑动时候容易漏掉一个或者几个Item 的高度,获取高度不准确,为了解决这个问题,笔者只好放弃保存总高度之和这个办法,只好用比较笨拙一点的 保存每个item的高度,然后for循环遍历取出每个item高度相加 ,然后减去FirstVisibleItem的gettop();思路大概就是这样。办法虽然有点笨重,但是确实可以用。如果有更好的解决办法欢迎告知笔者,互相学习。
下面是代码:
public class RecycleViewUtils { private WeakReference<RecyclerView> recycleView; private RecycleViewUtils utils; private Map<Integer, Integer> itemHeights; private int nowItemPos, totalHeight = 0, pos; private View nowView; private LinearLayoutManager layoutManager; public RecycleViewUtils() { } public RecycleViewUtils(RecyclerView recyclerView) { this.recycleView = new WeakReference<RecyclerView>(recyclerView); itemHeights = new WeakHashMap<>(); nowItemPos = 0; layoutManager = (LinearLayoutManager) recycleView.get().getLayoutManager(); } public RecycleViewUtils with(RecyclerView recyclerView) { if (utils == null) utils = new RecycleViewUtils(recyclerView); return utils; } public synchronized int getScrollY() { int pos = layoutManager.findFirstVisibleItemPosition(); int lastPos = layoutManager.findLastVisibleItemPosition(); for (int i = pos; i <= lastPos; i++) { nowView = layoutManager.findViewByPosition(i); if (!itemHeights.containsKey(i)) { totalHeight = 0; totalHeight += nowView.getHeight(); if (totalHeight == 0) break; itemHeights.put(i, totalHeight); } } // nowView = layoutManager.findViewByPosition(pos); // if (pos == nowItemPos) { // if (!itemHeights.containsKey(pos)) { // totalHeight = 0; // if (itemHeights.containsKey(pos - 1)) // totalHeight = itemHeights.get(pos - 1); // totalHeight += nowView.getMeasuredHeight(); // itemHeights.put(nowItemPos, totalHeight); // } // } int height = 0; // if (itemHeights.containsKey(pos - 1)) height = itemHeights.get(pos - 1); for (int i = 0; i < pos; i++) height += itemHeights.get(i); if (pos != nowItemPos) nowItemPos = pos; nowView = layoutManager.findViewByPosition(pos); if (nowView != null) height -= nowView.getTop(); return height; } }
用法就是初始化的时候
recycleViewUtils = new RecycleViewUtils().with(list_view);
然后在recycleview的onscroll方法里获取
recycleViewUtils.getScrollY()这样就可以获取到recycleview的滑动距离。