Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
826 views
in Technique[技术] by (71.8m points)

android - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...