2013-04-18 36 views
2

其中一個Android示例(FixedGridLayout)將ViewGroup擴展爲允許在將新項添加到網格時進行自定義轉換。代碼按預期工作,但不實現滾動。因此,我將整個佈局包裝在一個ScrollView期望這將解決問題。但是,看起來FixedGridLayout視圖實際上比它應該大得多,在項目之後留下了很多可滾動的空間。擴展ViewGroup時正確實施onMeasure()

我懷疑這個問題與onMeasure()的實現方式有關。我是對的嗎?如果是這樣,這個代碼有什麼問題?

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    int cellWidthSpec = MeasureSpec.makeMeasureSpec(mCellWidth, MeasureSpec.AT_MOST); 
    int cellHeightSpec = MeasureSpec.makeMeasureSpec(mCellHeight, MeasureSpec.AT_MOST); 

    int count = getChildCount(); 
    for (int index=0; index<count; index++) { 
     final View child = getChildAt(index); 
     child.measure(cellWidthSpec, cellHeightSpec); 
    } 

    // Use the size our parents gave us, but default to a minimum size to avoid 
    // clipping transitioning children 
    int minCount = count > 3 ? count : 3; 
    setMeasuredDimension(resolveSize(mCellWidth * minCount, widthMeasureSpec), 
      resolveSize(mCellHeight * minCount, heightMeasureSpec)); 
} 

回答

0

ScrollView只關心它的測量後,內子視圖的垂直高度,但它不會滾動,除非內孩子套高度的東西比父母更大。

您可以在內部視圖上調用getHeight()以查看它是否計算出比您預期的更大的值。該方法僅在佈局完成後纔有效。

您發佈的代碼確實似乎有錯誤。

int minCount = count > 3 ? count : 3; 
setMeasuredDimension(resolveSize(mCellWidth * minCount, widthMeasureSpec), 
     resolveSize(mCellHeight * minCount, heightMeasureSpec)); 

的代碼設置widthheight基於數量的孩子。如果我假設網格佈局模式,則寬度計算爲mCellWidth * columns,高度計算爲mCellHeight * rows

如果您使用兒童的總數設置高度值,那麼這將解釋爲什麼您的滾動超出佈局的底部。