發(fā)現(xiàn)問題
最近因為項目需要使用ScrollView來嵌套ListView和ExpandableListView,在開發(fā)過程中發(fā)現(xiàn)残拐,顯示的時候ListView不能完全正確的顯示,一種做法就是使ListView高度自適應(yīng)骆撇。
ScrollView嵌套ListView
/*
* 動態(tài)設(shè)置ListView高度
* @param listView
* @param adapter listView 的適配器
* */
public void setListHeight(ListView listView, Adapter adapter) {
if (adapter == null) {
return;
}
int totalHeight = 0;
/* adapter.getCount()返回數(shù)據(jù)項的數(shù)目*/
for (int i = 0; i < adapter.getCount(); i++) {
View itemView = adapter.getView(i, null, listView);
// 計算子項View 的寬高
itemView.measure(View.MeasureSpec.UNSPECIFIED , View.MeasureSpec.UNSPECIFIED);
// 統(tǒng)計所有子項的總高度
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呈現(xiàn)的效果類似QQ的好友分組
// ExpandListView 列表狀態(tài) 1展開 0關(guān)閉 該案例中設(shè)置為三級
int[] isExpand = new int[] { 0, 0, 0 };
// 通過監(jiān)聽展開和關(guān)閉事件動態(tài)設(shè)置高度
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自適應(yīng)高度 根據(jù)子項數(shù)量
* @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);
}