GridView、listView的高度为Wrap_content,高度包裹内容使用Integer.MAX_VALUE >> 2的原因

    在一般情况下使用GridView、listView其实都是高度填充父类窗体(fill_parent、match_parent),那么UI显示正常

 不过,当在这个外面嵌套一个垂直方向滚动的布局(ScrollView)之后,特殊情况就出现了。listview的滑动冲突。gridView的显示一行等

 

网上已经有理想的解决方案如下:

   @Override
     protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec) {
         int heightSpec;
  
         if (getLayoutParams().height == LayoutParams.WRAP_CONTENT) {
             // The great Android "hackatlon", the love, the magic.
             // The two leftmost bits in the height measure spec have
             // a special meaning, hence we can't use them to describe height.
             heightSpec = MeasureSpec.makeMeasureSpec(
                    Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
         }
         else {
             // Any other height should be respected as is.
             heightSpec = heightMeasureSpec;
         }
  
         super .onMeasure(widthMeasureSpec, heightSpec);
     }

 
重写listVIew、gridView的onMeasure方法就行了,加上红字部分就可以实现listView、gridView高度包裹内容。
 为什么是
            MeasureSpec.makeMeasureSpec(
                    Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
 
首先得看看 MeasureSpec 的几个方法和作用
这篇文章已经详细介绍
 
那么其中的两个值就很好理解了
因为32位的数据中的前两位是代表的模式,那么 Integer.MAX_VALUE >> 2就代表能获取到的最大值(不含模式下的值)
MeasureSpec.AT_MOST这个模式下面高度会在listView、gridView的item集高度和Integer.MAX_VALUE >> 2
之间取最小值,也就是包裹内容
 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值