ScrollView中包含ListView时,ListView会出现不能滑动的问题,因为默认两个滑动控件不能嵌套,要让ListView正常显示,需要计算ListView的高度
这里是计算方法,原理是获取每个item的高度,相加,如果有header和footer也要加上
1 /** 2 * ScrollView和ListView共存时,该方法用于计算ListView高度 3 * 4 * @param listView 5 */ 6 public void setListViewHeightBasedOnChildren(ListView listView) { 7 ListAdapter listAdapter = listView.getAdapter(); 8 if (listAdapter == null) { 9 return;10 }11 12 int totalHeight = 0;13 for (int i = 0; i < listAdapter.getCount(); i++) {14 View listItem = listAdapter.getView(i, null, listView);15 listItem.measure(0, 0);16 totalHeight += listItem.getMeasuredHeight();17 }18 19 ViewGroup.LayoutParams params = listView.getLayoutParams();20 params.height = totalHeight21 + (listView.getDividerHeight() * (listAdapter.getCount() - 1));22 ((MarginLayoutParams) params).setMargins(10, 10, 10, 10);23 listView.setLayoutParams(params);24 }
在类文件中使用:
1 ListViewAdapter listViewAdapter = new ListViewAdapter(this);2 mListView.setAdapter(listViewAdapter);3 listViewAdapter.setListViewHeightBasedOnChildren(mListView);
另一种解决方法是自定义LinearLayout,通过addView动态添加view.
收藏