Android getting exact scroll position in ListView

前端 未结 8 1228
误落风尘
误落风尘 2020-12-01 02:56

I\'d like to get the exact, pixel position of the ListView scroll. And no, I am not referring to the first visible position.

Is there a way to achieve this?

8条回答
  •  再見小時候
    2020-12-01 03:14

    I know I'm late to the party but I felt like sharing my solution to this problem. I have a ListView and I was trying to find how much I have scrolled in order to scroll something else relative to it and cause a parallax effect. Here's my solution:

    public abstract class OnScrollPositionChangedListener implements AbsListView.OnScrollListener {
        int pos;
        int prevIndex;
        int prevViewPos;
        int prevViewHeight;
        @Override
        public void onScroll(AbsListView v, int i, int vi, int n) {
            try {
                View currView = v.getChildAt(0);
                int currViewPos = Math.round(currView.getTop());
                int diffViewPos = prevViewPos - currViewPos;
                int currViewHeight = currView.getHeight();
                pos += diffViewPos;
                if (i > prevIndex) {
                    pos += prevViewHeight;
                } else if (i < prevIndex) {
                    pos -= currViewHeight;
                }
                prevIndex = i;
                prevViewPos = currViewPos;
                prevViewHeight = currViewHeight;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                onScrollPositionChanged(pos);
            }
        }
        @Override public void onScrollStateChanged(AbsListView absListView, int i) {}
        public abstract void onScrollPositionChanged(int scrollYPosition);
    }
    

    I created my own OnScrollListener where the method onScrollPositionChanged will be called every time onScroll gets called. But this method will have access to the calculated value representing the amount that the ListView has been scrolled.

    To use this class, you can setOnClickListener to a new OnScrollPositionChangedListener and override the onScrollPositionChanged method.

    If you need to use the onScroll method for other stuff then you can override that too but you need to call super.onScroll to get onScrollPositionChanged working correctly.

    myListView.setOnScrollListener(
        new OnScrollPositionChangedListener() {
            @Override
            public void onScroll(AbsListView v, int i, int vi, int n) {
                super.onScroll(v, i, vi, n);
                //Do your onScroll stuff
            }
            @Override
            public void onScrollPositionChanged(int scrollYPosition) {
                //Enjoy having access to the amount the ListView has scrolled
            }
        }
    );
    

提交回复
热议问题