最近在码代码的过程中将ScrollView内嵌套了ListView使用,结果出现一个问题,就是在ListView只显示了一两行,通过查阅资料发现是因为当ScrollView嵌套ListView时无法正确计算ListView的大小,在网上查阅资料后找到了几种解决办法,现总结如下:
1.在ScrollView中将android:fillViewport属性设置为"true",此方法适用于ScrollView中内容不是很多的情况,一般不使用;
2.当ListView处于ScrollView的最下部时,可以在代码中获取到ListView的属性,并将高度设置为Integer.MAX_VALUE;
3.当ListView不在ScrollView的最下部时,方法2不适用,此时需要在手动设置listview.setadapter()或者listview.notifyDataSetChangded后手动设置ListView的高度,代码如下:
private void setListViewHeightBasedOnChildren(ListView listView) {
MyRecentWeatherAdapter<RecentWeather> adapter = (MyRecentWeatherAdapter<RecentWeather>) listView.getAdapter();
if (adapter == null) {
return;
}
int totalHeight = 0;
Log.d("<<", "---->>itemcount " + adapter.getCount());
for (int i = 0, len = adapter.getCount(); i < len; i++) {
<span style="white-space:pre"> </span>View listItem = adapter.getView(i, null, listView);
<span style="white-space:pre"> </span>// 计算子项View的宽高
<span style="white-space:pre"> </span>listItem.measure(0, 0);
<span style="white-space:pre"> </span>// 统计所有子项的总高度
<span style="white-space:pre"> </span>totalHeight += listItem.getMeasuredHeight();
<span style="white-space:pre"> </span>}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
//listView.getDividerHeight()获取子项间分隔符占用的高度
//params.height最后得到整个ListView完整显示需要的高度
listView.setLayoutParams(params);
}