public static void setListViewHeightBasedOnChilds(ListView listView){ ListAdapter listAdapter = listView.getAdapter(); if(listAdapter==null){ return; } int totalHeight=0; int totalDividerHeight=0; for(int i = 0;i<listAdapter.getCount();i++){ View listItem=listAdapter.getView(i, null, listView); listItem.measure(0,0); totalHeight+=listItem.getMeasuredHeight(); } totalDividerHeight=listView.getDividerHeight()*(listAdapter.getCount()-1); ViewGroup.LayoutParams params=listView.getLayoutParams(); params.height=totalHeight+totalDividerHeight; listView.setLayoutParams(params); }
亲测可用。
时间: 2024-09-30 14:59:12