Android GridView設置行數


普通的做法是設置一個高度,然后里面能顯示出來幾行就是幾行,如果里面的內容高度變了,就需要重新調整高度來適配。

觀察了一下它的onMeasure

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

.....

if (heightMode == MeasureSpec.AT_MOST) {
    int ourSize =  mListPadding.top + mListPadding.bottom;
   
    final int numColumns = mNumColumns;
    for (int i = 0; i < count; i += numColumns) {
        ourSize += childHeight;
        if (i + numColumns < count) {
            ourSize += mVerticalSpacing;
        }
        if (ourSize >= heightSize) {
            ourSize = heightSize;
            break;
        }
    }
    heightSize = ourSize;
}
...

}

發現,如果是它設置wrap_content,可以通過改變它的adapter來確定行數,具體方法如下是:

MyAdapter

@Override
    public int getCount() {
        if (mIsOnMeasure && super.getCount() >MAX_COUNT) {
            return MAX_COUNT;
        }
        return super.getCount();
    }


    public void setOnMeasureStatus(boolean isOnMeasure) {
        mIsOnMeasure = isOnMeasure;
    }





Gridview- >

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightMode == MeasureSpec.AT_MOST) {
            ((MyAdapter) getAdapter()).setOnMeasureStatus(true);
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int height = getMeasuredHeight();
            ((FolderAdapter) getAdapter()).setOnMeasureStatus(false);
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            setMeasuredDimension(getMeasuredWidthAndState(),
                    MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

在onMeasure的時候,先讓adapter假裝有行數×列數的內容,調用 super.onMeasure先算出一個高,這個就是期望高度。

然后在調用一次  super.onMeasure(widthMeasureSpec, heightMeasureSpec),把整個view繪制出來
最后通過setMeasuredDimension就可以做到了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM