ListView 设置高度为刚好能包裹子元素
当我们的程序中有多个ListView 时怎么设置ListView 的高度成了一个问题。 ListView中数据个数是不确定的,显然不能将高度写死。 但通过测试发现,无论将高度设置为匹配父控件还是包裹内容,都不能正常显示所有内容。 通过在网上查找资料,我找到如下解决办法。 首先将多个ListView包裹在LinerLayout中,然后将LinerLayou放到ScrollView中。这样多个ListView 就可以滚动了。 关于ListView 的高度,用以下代码可以设置
private void setListViewHeightBasedOnChildren(ListView listView){ ListAdapter adapter = listView.getAdapter(); if(adapter == null){ return; } int totalHeight = 0; for(int i=0;i<adapter.getCount();i++){ View listItem = adapter.getView(i,null,listView); .getResources().getDisplayMetrics().widthPixels, View.MeasureSpec.EXACTLY), 0); //此处很重要,不要用measure(0,0);否则item中如果有换行,显示不完全 totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight+(listView.getDividerHeight()*(adapter.getCount()-1)); listView.setLayoutParams(params); }