如何从 GridView 获取滚动位置? [英] How to get scroll position from GridView?

查看:36
本文介绍了如何从 GridView 获取滚动位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建我自己的网格视图函数 - 在 GridView 上扩展.我唯一无法解决的是如何获取 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() 确实总是返回 0,并且 onScrollListener 的参数只是可见子视图的范围,而不是实际的滚动位置.

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.

这里有人有想法吗?

推荐答案

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

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.

注意:

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

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

Hope that helps and gives you an idea.

这篇关于如何从 GridView 获取滚动位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆