如何从GridView获取滚动位置?

mAx*_*mAx 19 android scroll gridview position scroll-offset

我正在尝试构建自己的网格视图函数 - 扩展GridView.我唯一无法解决的是如何获得当前的滚动位置GridView.

getScrollY()总是返回0,并且onScrollListener参数只是一系列可见的子视图,而不是实际的滚动位置.

这似乎并不困难,但我在网上找不到解决方案.

这里有谁有想法?

Chr*_*oph 13

我没有找到任何好的解决方案,但是这个至少能够保持滚动位置像素完美:

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);
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您无法获得绝对滚动位置,而是可见项目+位移对.

笔记:

  • 这适用于API 8+.
  • 你可以在API 16+中使用mGrid.getVerticalSpacing().
  • 您可以在API 11+中使用mGrid.smoothScrollToPositionFromTop(index,offset)而不是最后两行.

希望有所帮助并给你一个想法.