Scroll offset of GridView
Asked Answered
J

2

5

Is there a way to determine the current scroll offset or scroll position of a GridView?

View.getScrollY() // Underlying var is not updated during a scroll.

I have tried setting an OnScrollListener but the onScroll callback is not fine grained enough for my purposes.

Here is the how I'm attempting to determine the scroll offset using an OnScrollListener.

private int getScrollY() {
    int top = 0;
    if (mGridView.getChildCount() > 0) {
        final View firstView = mGridView.getChildAt(0);
        top = firstView.getTop();
    }
    return top;
}

The issue with this code is that the returned y offset is inaccurate when scrolling upwards; the top view is recycled and hence, the y offset seems to jump;

Is there a nice way of calculating the scroll offset of a GridView? I can't seem to find a good solution.

Jacy answered 3/7, 2013 at 16:14 Comment(0)
C
4

Use this.

public class CustomGridView extends GridView {

    public CustomGridView(Context context) {
        super(context);
    }

    public CustomGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /* ADD THIS */
    @Override
    public int computeVerticalScrollOffset() {
        return super.computeVerticalScrollOffset();
    }
}

Returns an int value when called

Chutzpah answered 3/3, 2015 at 19:44 Comment(6)
Oh thanks for answering this! I had forgot to answer it myself after figuring it out.Jacy
@Jacy This seems to give a correct Y offset. But which function do you use to set the Gridview to the same offset? I have tried quite a few, and can't get the correct results. Always end up in different positions. I'm guessing, this isn't as straightforward as I thought it would be.Showman
gridview.smoothScrollToPosition(int index)Jacy
@Jacy Yeah.. had already tried that one, it's not pixel perfect.. This is way harder then it should be..Showman
Does GridView have any computeVerticalScrollOffset method? Android Studio does not offer it.Reames
@János I believe the offset is accessed via a private method. You'll need to create a custom class (Like above) to access it. Or you could use a RecyclerView.Chutzpah
M
1

You can use GridView.getFirstVisiblePosition().

http://developer.android.com/reference/android/widget/AdapterView.html#getFirstVisiblePosition()

Metameric answered 3/7, 2013 at 16:17 Comment(3)
"The issue with this code is that the returned y offset is inaccurate when scrolling upwards; the top view is recycled and hence, the y offset seems to jump;"Jacy
Basically, you can't use the first visible cell's top attribute as a way to manage the scroll. The moment a view is recycled, you have a jump with an upper bound equal to cell.getHeight()Jacy
This solution does work, but only if every cell has the same height.Jacy

© 2022 - 2024 — McMap. All rights reserved.