今天又有同事遇到嵌套問題,在ScoreView嵌套listview時候,或者Listview嵌套Listview,item條目顯示不全,往往只顯示一條。
這是listview在填充是動態繪製item佈局時候衝突造成的,我們在嵌套的時侯需要動態計算每個item條目的高度
獲取listview單個條目高度:
listView.getDividerHeight()
獲取listview的條目數量:
listAdapter.getCount() - 1
listview的高度就獲取到了
params.height = totalHeight +30+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
整體代碼如下:
public class ListScoreViewHelper {
public static void setListViewHeightBasedOnChildren(ListView listView){
if (listView==null) return;
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight +30+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}