【问题标题】:How to get scroll position from GridView?如何从 GridView 获取滚动位置?
【发布时间】:2013-09-10 15:03:09
【问题描述】:

我正在尝试构建自己的网格视图功能 - 在 GridView 上进行扩展。 我唯一无法解决的是如何获取GridView的当前滚动位置。

getScrollY() 总是返回 0,onScrollListener 的参数只是可见子视图的范围,而不是实际的滚动位置。

这似乎不是很困难,但我只是在网上找不到解决方案。

这里有人有想法吗?

【问题讨论】:

    标签: android gridview scroll position scroll-offset


    【解决方案1】:

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

    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);
    

    这样你不能得到一个绝对的滚动位置,而是一个可见的项目+位移对。

    注意事项:

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

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

    【讨论】:

    • 容器代表什么东西?请告诉我
    • 根据我模糊的记忆,这是一个复制/粘贴错误,应该是 mGrid。
    • @SalmanAshraf 包含元素的视图,否则尝试 mGrid
    • 垂直间距是什么意思?
    • @Attila Molnár 不客气 - 我真的很惊讶这仍然有用,并且实际工作 4.5 年和十几个 API 版本。
    【解决方案2】:

    在 Gingerbread 上,GridView getScrollY() 在某些情况下有效,而在某些情况下则无效。这是基于第一个答案的替代方案。必须知道行高和列数(并且所有行的高度必须相同):

    public int getGridScrollY()
    {
       int pos, itemY = 0;
       View view;
    
       pos = getFirstVisiblePosition();
       view = getChildAt(0);
    
       if(view != null)
          itemY = view.getTop();
    
       return YFromPos(pos) - itemY;
    }
    
    private int YFromPos(int pos)
    {
       int row = pos / m_numColumns;
    
       if(pos - row * m_numColumns > 0)
          ++row;
    
       return row * m_rowHeight;
    }
    

    第一个答案还为如何对 GridView 进行像素滚动提供了一个很好的线索。这是一个通用的解决方案,它将滚动一个等效于 scrollTo(0, scrollY) 的 GridView:

    public void scrollGridToY(int scrollY)
    {
       int row, off, oldOff, oldY, item;
    
       // calc old offset:
       oldY = getScrollY(); // getGridScrollY() will not work here
       row = oldY / m_rowHeight;
       oldOff = oldY - row * m_rowHeight;
    
       // calc new offset and item:
       row = scrollY / m_rowHeight;
       off = scrollY - row * m_rowHeight;
       item = row * m_numColumns;
    
       setSelection(item);
       scrollBy(0, off - oldOff);
    }
    

    这些函数在子类 GridView 中实现,但它们可以很容易地重新编码为外部。

    【讨论】:

    • 修复了第一个示例中的错误。
    • 上面的第一个代码块对我有用。我必须进行的一项调整是将网格的顶部填充 [getPaddingTop()] 添加到计算值。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-04-08
    • 2014-02-23
    • 2012-03-18
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    相关资源
    最近更新 更多