GridView的高度自适应


接着上面一篇文章。

当GridView不知道parent高度的时候,也就是MeasureSpec是UNSPECIFIED,这个时候,GridView高度为第一个child的高度,并显示滚动条。

 1         mItemCount = mAdapter == null ? 0 : mAdapter.getCount();
 2         final int count = mItemCount;
 3         if (count > 0) {
 4             final View child = obtainView(0, mIsScrap);
 5 
 6             AbsListView.LayoutParams p = (AbsListView.LayoutParams) child.getLayoutParams();
 7             if (p == null) {
 8                 p = (AbsListView.LayoutParams) generateDefaultLayoutParams();
 9                 child.setLayoutParams(p);
10             }
11             p.viewType = mAdapter.getItemViewType(0);
12             p.forceAdd = true;
13 
14             int childHeightSpec = getChildMeasureSpec(
15                     MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0, p.height);
16             int childWidthSpec = getChildMeasureSpec(
17                     MeasureSpec.makeMeasureSpec(mColumnWidth, MeasureSpec.EXACTLY), 0, p.width);
18             child.measure(childWidthSpec, childHeightSpec);
19 
20             childHeight = child.getMeasuredHeight();
21             childState = combineMeasuredStates(childState, child.getMeasuredState());
22 
23             if (mRecycler.shouldRecycleViewType(p.viewType)) {
24                 mRecycler.addScrapView(child, -1);
25             }
26         }
27         
28         if (heightMode == MeasureSpec.UNSPECIFIED) {
29             heightSize = mListPadding.top + mListPadding.bottom + childHeight +
30                     getVerticalFadingEdgeLength() * 2;
31         }
32 
33         if (heightMode == MeasureSpec.AT_MOST) {
34             int ourSize =  mListPadding.top + mListPadding.bottom;
35            
36             final int numColumns = mNumColumns;
37             for (int i = 0; i < count; i += numColumns) {
38                 ourSize += childHeight;
39                 if (i + numColumns < count) {
40                     ourSize += mVerticalSpacing;
41                 }
42                 if (ourSize >= heightSize) {
43                     ourSize = heightSize;
44                     break;
45                 }
46             }
47             heightSize = ourSize;
48         }

我们可以发现,确实是只设置为第一个child的高度,当MeasureSpec是AT_MOST的时候,才会读取所有child的高度。

再网上,搜到了下面的办法。

 1 heightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE, MeasureSpec.AT_MOST); 

其实这是不对的,MeasureSpec的前两个bits是mode,size的大小不能超过30位。于是,稍微修改,size设置为1000000,应该是足够了,当不足够的时候,你的app如果还没更新早就该被淘汰了。

 1 heightMeasureSpec = MeasureSpec.makeMeasureSpec(1000000, MeasureSpec.AT_MOST); 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM