如何从GridView获取滚动位置?

时间:2011-05-25 13:13:49

标签: android gridview scroll position scroll-offset

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

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

这似乎并不困难,但我无法在网络上找到解决方案。

这里有谁有想法?

2 个答案:

答案 0 :(得分:12)

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

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),而不是最后两行。

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

答案 1 :(得分:0)

在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提供了一个很好的线索。这是一个通用解决方案,它将滚动GridView等效于scrollTo(0,scrollY):

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中实现,但它们可以很容易地重新编码为外部函数。

相关问题