• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
常春藤的博客
   首页    新随笔       管理    订阅  订阅

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

posted @ 2015-06-11 11:59  常春藤的博客  阅读(5747)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3