2011-05-25 103 views
17

我想建立自己的網格視圖功能 - 在GridView上延伸。 我無法解決的唯一問題是如何獲得GridView的當前滾動位置。如何從GridView獲取滾動位置?

getScrollY()總是返回0,而onScrollListener的參數只是可見子視圖的範圍,而不是實際的滾動位置。

這似乎並不困難,但我無法在網上找到解決方案。

這裏有誰有想法?

回答

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)而不是最後兩行。

希望能夠幫助並給你一個想法。

+0

容器代表哪個東西? 請告訴我 – 2013-03-11 10:37:51

+0

從我的模糊記憶這是一個複製/粘貼錯誤,應該是mGrid。 – Christoph 2013-03-11 18:48:41

+0

@SalmanAshraf包含元素的視圖,請嘗試mGrid,否則 – 2013-11-30 12:50:26

0

關於薑餅,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內實現,但它們可容易地重新編碼爲外部。

+0

修復了第一個例子中的錯誤。 – dslamnig 2013-05-17 01:21:19