android中listview的getView方法不調用的一種狀況

1,個人ListView是放在一個ScrollView中的,listView中加了一個HeaderView(頭佈局)。你們都知道在ScrolleView中使用ListView須要計算listview每一個item的高度,否則的話,listview只會顯示一個item。因此我在初始化的時候調用了下面的方法計算了listView  item 的高度:java

public void setListViewHeightBasedOnChildren(ListView listView) {服務器

// 獲取ListView對應的Adapteride

ListAdapter homeAdapter = listView.getAdapter();佈局

if (homeAdapter == null) {spa

return;debug

}指針

int totalHeight = 0;調試

for (int i = 0, len = homeAdapter.getCount(); i < len; i++) {code

// listAdapter.getCount()返回數據項的數目get

View listItem = homeAdapter.getView(i, null, listView);

// 計算子項View 的寬高

listItem.measure(0, 0);

int childHeight = listItem.getMeasuredHeight();

// 統計全部子項的總高度

totalHeight += childHeight;

}


ViewGroup.LayoutParams params = listView.getLayoutParams();

params.height = totalHeight + (listView.getDividerHeight() * (homeAdapter.getCount() - 1));

// listView.getDividerHeight()獲取子項間分隔符佔用的高度

// params.height最後獲得整個ListView完整顯示須要的高度

listView.setLayoutParams(params);

}

在我沒有用數據調試的時候沒有任何問題。當從服務器拿到數據,而後通知adapter.notifyDataSetChanged();的時候,問題出現了,adapter的getCount()調用,而getView()怎麼都不調用,瞎折騰了兩小時以後,豁然開朗,原來計算listview中item的高度須要在調用了adapter.notifyDataSetChanged();這個以後去計算,以前沒有數據listView根本不知道本身有多少item。

etListViewHeightBasedOnChildren(mListView)挪到adapter.notifyDataSetChanged()後面,一切正常。


另外,若是listview有headerView的話,計算的時候,headView的高度也須要計算。若是headerView中有一些佈局須要有數據時顯示,沒數據時不顯示的話,就須要根據數據來計算他顯示的佈局的高度:以下方法:

public void setListViewHeightBasedOnChildren(ListView listView) {
		// 獲取ListView對應的Adapter
		ListAdapter homeAdapter = listView.getAdapter();
		if (homeAdapter == null) {
			return;
		}

		int totalHeight = 0;
		for (int i = 0, len = homeAdapter.getCount(); i < len; i++) {
			// listAdapter.getCount()返回數據項的數目
			View listItem = homeAdapter.getView(i, null, listView);
			// 計算子項View 的寬高
			listItem.measure(0, 0);
			int childHeight ;
			if (i == 0) {//是header視圖
				if (GlobalVariable.mLabels.size() < 3) {
					childHeight = listItem.getMeasuredHeight();
				}else if (GlobalVariable.mLabels.size() < 6) {
					childHeight = listItem.getMeasuredHeight()*2;
				}else {
					childHeight = listItem.getMeasuredHeight()*3;
				}
			}else{
				childHeight = listItem.getMeasuredHeight();
			}
			// 統計全部子項的總高度
			totalHeight += childHeight;
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (homeAdapter.getCount() - 1));
		// listView.getDividerHeight()獲取子項間分隔符佔用的高度
		// params.height最後獲得整個ListView完整顯示須要的高度
		listView.setLayoutParams(params);
	}

跟上面不一樣的是,我計算了headview中每一個子佈局的高度


後續附加:


ListView 跟ScroolView 共存 listItem.measure(0, 0) 空指針

我每次調用的時候都會產生在listItem.measure(0,0)報空指針異常。我debug 發現listItem 並非爲空啊,
爲啥會報錯。在通過一番查找以後。我發現原來是本身item的佈局用了RelativeLayout 把他換爲LinearLayout 就行了。
究其緣由,原來是 Linearlayout重寫了onmeasure方法,其餘的佈局文件沒有重寫onmeasure,因此在調用listItem.measure(0, 0);
 會報空指針異常,若是想用這個東東,就必須用linearlayout佈局嘍。