思路:循环取得listview中的Item的高度,把所有Item高度累加,就是Listview的高度。
1 public static void setListViewHeightBasedOnChildren(ListView listView) { 2 if (listView == null) 3 return; 4 ListAdapter listAdapter = listView.getAdapter(); 5 if (listAdapter == null) { 6 return; 7 } 8 int totalHeight = 0; 9 for (int i = 0; i < listAdapter.getCount(); i++) { 10 View listItem = listAdapter.getView(i, null, listView); 11 listItem.measure(0, 0); 12 totalHeight += listItem.getMeasuredHeight(); 13 } 14 ViewGroup.LayoutParams params = listView.getLayoutParams(); 15 params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); 16 listView.setLayoutParams(params); 17 }
时间: 2024-10-06 17:35:37