发现问题
最近因为项目需要使用ScrollView来嵌套ListView和ExpandableListView,在开发过程中发现,显示的时候ListView不能完全正确的显示,一种做法就是使ListView高度自适应。
ScrollView嵌套ListView
/*
* 动态设置ListView高度
* @param listView
* @param adapter listView 的适配器
* */
public void setListHeight(ListView listView, Adapter adapter) {
if (adapter == null) {
return;
}
int totalHeight = 0;
/* adapter.getCount()返回数据项的数目*/
for (int i = 0; i < adapter.getCount(); i++) {
View itemView = adapter.getView(i, null, listView);
// 计算子项View 的宽高
itemView.measure(View.MeasureSpec.UNSPECIFIED , View.MeasureSpec.UNSPECIFIED);
// 统计所有子项的总高度
totalHeight += itemView.getMeasuredHeight();
}
/*
* listView.getDividerHeight()获取子项间分隔符占用的高度
* params.height最后得到整个ListView完整显示需要的高度
* */
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
listView.setLayoutParams(params);
}
ScrollView嵌套ExpandableListView
ExpandableListView呈现的效果类似QQ的好友分组
// ExpandListView 列表状态 1展开 0关闭 该案例中设置为三级
int[] isExpand = new int[] { 0, 0, 0 };
// 通过监听展开和关闭事件动态设置高度
listView.setOnGroupExpandListener(new OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
isExpand[groupPosition] = 1;
setListHeight(listView, listAdapter);
}
});
listView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int groupPosition) {
isExpand[groupPosition] = 0;
setListHeight(listView, listAdapter);
}
});
/*
* ExpandListView自适应高度 根据子项数量
* @param listView
* @param listAdapter listView 的适配器
* */
public void setListHeight(ExpandableListView listView, Adapter listAdapter) {
if (listAdapter == null) {
return;
}
int totalHeight = 0;
int total = 0;
View listItem;
for (int i = 0; i < listAdapter.getGroupCount(); i++) {
listItem = listAdapter.getGroupView(i, false, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
total += (listAdapter.getChildrenCount(0) - 1);
}
for(int i = 0; i < isExpand.lenght ; i++) {
if (isExpand[i] == 1)
for (int j = 0; j < listAdapter.getChildrenCount(i); j++) {
listItem = listAdapter.getChildView(i, j, false, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
total += (listAdapter.getChildrenCount(i) - 1);
}
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * total);
listView.setLayoutParams(params);
}
作者:黄伟杰
原文链接:ScrollView嵌套下ListView或ExpandableListView的高度自适应