How to get the scroll speed on a ListView?

前端 未结 6 1441
逝去的感伤
逝去的感伤 2020-12-13 15:09

I have a ListView with onScrollStateChanged and onScroll event listeners. I want to be able to get the scroll speed of the ListView or some way to get the finalX location of

6条回答
  •  无人及你
    2020-12-13 15:27

    Here's the code if you need to know how many pixels per second it's scrolling when the items have different sizes or when you have a very long list. Calculating and caching each item size would not work if some items are missed. BTW if you choose that method, you should cache the item offset instead of the height so you don't have to do so many calculation.

    Override OnScrollListener:

    private HashMap offsetMap = new HashMap<>();
    private long prevScrollTime = System.currentTimeMillis();
    
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            float traveled = 0;
            Set oldKeys = new HashSet<>(offsetMap.keySet());
            for (int i = 0; i < visibleItemCount; i++) {
                int pos = firstVisibleItem + i;
                int newOffset = view.getChildAt(i).getTop();
                if (offsetMap.containsKey(pos) && traveled == 0) {
                    traveled = Math.abs(newOffset - offsetMap.get(pos));
                }
                offsetMap.put(pos, newOffset);
                oldKeys.remove(pos);
            }
            // remove those that are no longer in view
            for (Integer key : oldKeys) {
                offsetMap.remove(key);
            }
            long newTime = System.currentTimeMillis();
            long t = newTime - prevScrollTime;
            if (t > 0) {
                float speed = traveled / t * 1000f;
            } else {
                // speed = 0
            }
            prevScrollTime = newTime;
    }
    

提交回复
热议问题