Search code examples
androidgridviewscrollpositionscroll-offset

How to get scroll position from GridView?


I am trying to build my own grid view functions - extending on the GridView. The only thing I cannot solve is how to get the current scroll position of the GridView.

getScrollY() does always return 0, and the onScrollListener's parameters are just a range of visible child views, not the actual scroll position.

This does not seem very difficult, but I just can't find a solution in the web.

Anybody here who have an idea?


Solution

  • I did not find any good solution, but this one is at least able to maintain the scroll position kind of pixel-perfectly:

    int offset = (int)(<your vertical spacing in dp> * getResources().getDisplayMetrics().density); 
    int index = mGrid.getFirstVisiblePosition();
    final View first = container.getChildAt(0);
    if (null != first) {
        offset -= first.getTop();
    }
    
    // Destroy the position through rotation or whatever here!
    
    mGrid.setSelection(index);
    mGrid.scrollBy(0, offset);
    

    By that you can not get an absolute scroll position, but a visible item + displacement pair.

    NOTES:

    • This is meant for API 8+.
    • You can get with mGrid.getVerticalSpacing() in API 16+.
    • You can use mGrid.smoothScrollToPositionFromTop(index, offset) in API 11+ instead of the last two lines.

    Hope that helps and gives you an idea.