1. 程式人生 > >GridView、listView的高度為Wrap_content,高度包裹內容使用Integer.MAX_VALUE >> 2的原因

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 之間取最小值,也就是包裹內容