在一般情况下使用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) {
heightSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >>
2
, MeasureSpec.AT_MOST);
}
else
{
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
之间取最小值,也就是包裹内容