网上关于怎样在ScrollView中嵌套ListView的讨论有很多,我大概是搜索了一下,简单总结如下:
2. 重写ListView的onMeasure方法,重新计算每个子Item的高度
- 不要在ScrollView中嵌套ListView
- a.用一个LinearLayout来代替ListView。里面的item通过addView添加进去。
- b.不用ScrollView,整个界面用一个ListView。ListView上面和下面的内容通过addHeaderView和addFooterView添加到ListView里。( 有时候采用这种方式不错的。)
- 非要在ScrollView中嵌套一个ListView。
- a.继承ListView重写一个类,在ListView的onMeasure方法里自己来计算ListView的高度。
- b.在代码中通过ListView的adapter中item的个数计算得出ListView应该的高度,然后通过setLayoutParam来指定ListView的高度。
- 但是上面所说的两种在ScrollView中嵌套ListView的方法都存在一个通用的bug:当光标在ListView中移动时ScrollView不能一起滚动
所以,在android的开发中还是要尽最大的努力去避免在ScrollView中嵌套ListView
下面是第二种情况的具体的实现:解决方法:
1:手动计算ListView高度(这里使用measuredHeight获取高度,measuredHeight并不是实际高度,因此该方法计算出的高度与实际的高度会有误差。),方法如下:
private void setListViewHeight(ListView listView) {
//获取ListView对应的Adapter
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; i++) { //listAdapter.getCount()返回数据项的数目
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0); //计算子项View 的宽高
totalHeight += listItem.getMeasuredHeight(); //统计所有子项的总高度
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
//listView.getDividerHeight()获取子项间分隔符占用的高度
//params.height最后得到整个ListView完整显示需要的高度
listView.setLayoutParams(params);
}
2. 重写ListView的onMeasure方法,重新计算每个子Item的高度
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//根据模式计算每个child的高度和宽度
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}