今天介紹一下怎么動態的獲取listview的高度。看代碼:
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的高度,需要注意一下幾個問題:
1、listview的item的根布局一定要是LinearLayout;
2、調用這個方法需要在適配器數據加載更新之后;代碼如下:
mAdapter.notifyDataSetChanged(); Function.getTotalHeightofListView(mListView);
3、獲取item的高度也可以用注釋掉的代碼,效果一樣的。