GridView、listView的高度為Wrap_content,高度包裹內容使用Integer.MAX_VALUE >> 2的原因
阿新 • • 發佈:2019-01-01
在一般情況下使用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的幾個方法和作用
這篇文章
2就代表能獲取到的最大值(不含模式下的值)
MeasureSpec.AT_MOST這個模式下面高度會在listView、gridView的item集高度和Integer.MAX_VALUE >>
2
之間取最小值,也就是包裹內容