1、在不知道ListView的Item個數時,用這種方法獲取Listview的高度
/**
* 獲取listview item高度
*
* @param listView
*/
public static void setListViewHeightBasedOnChildren(ListView listView) {
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);
// ListView的每個Item必須是LinearLayout,不能是其他的,因爲其他的Layout(如RelativeLayout)沒有重寫onMeasure(),這裏onMeasure()時拋出異常。
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
totalHeight += 10;
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
listView.setLayoutParams(params);
}
ListView lv = (ListView) findViewById(R.id.list);
SimpleAdapter sap = new SimpleAdapter(this, al, R.layout.list_item,
new String[] { "name", "icon" }, new int[] { R.id.title,R.id.icon });
lv.setAdapter(sap);
setListViewHeightBasedOnChildren(lv)
2、 listview個數較少,
在ScrollView中添加一屬性 android:fillViewport="true" ,這樣就可以讓ListView全屏顯示了
指定ListView的總高度 android:layout_height="450dp" ;
指定ListView的Item高度 android:layout_height="45dp"