public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); // listItem.measure(0, 0); listItem.measure( MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); }
使用這個代碼來獲取listview的高度,須要注意一下幾個問題:
一、listview的item的根佈局必定要是LinearLayout;
二、調用這個方法須要在適配器數據加載更新以後;
代碼以下:
mAdapter.notifyDataSetChanged();
Function.getTotalHeightofListView(mListView);
三、獲取item的高度也能夠用註釋掉的代碼,效果同樣的java