Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get scroll position from GridView?

Tags:

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?

like image 286
mAx Avatar asked May 25 '11 13:05

mAx


2 Answers

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.

like image 65
Christoph Avatar answered Sep 27 '22 01:09

Christoph


On Gingerbread, GridView getScrollY() works in some situations, and in some doesn't. Here is an alternative based on the first answer. The row height and the number of columns have to be known (and all rows must have equal height):

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

The first answer also gives a good clue on how to pixel-scroll a GridView. Here is a generalized solution, which will scroll a GridView equivalent to 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);
}

The functions are implemented inside a subclassed GridView, but they can be easily recoded as external.

like image 31
dslamnig Avatar answered Sep 26 '22 01:09

dslamnig