How to get scroll position from GridView?

后端 未结 2 538
轮回少年
轮回少年 2020-12-15 20:10

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

2条回答
  •  一生所求
    2020-12-15 20:33

    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)( * 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.

提交回复
热议问题