在以前一個項目中碰到這麼一個需求,要將一個ListView嵌套在一個外部ScrollView當中,試了後發現,ListView的高度出了問題,始終只顯示一點,並且滑動也有問題,Android預設是禁止將ListView潛逃在ScrollView裡面的,雖然這種設計不被推崇,但是後來到Stackoverflow上找到了一個解決方案,那就是在為ListView設定Adapter後,重新計運算元item的高度,然後通過LayoutParams重新給ListView設定高度,這樣就能正常顯示了。當然以上問題在iOS開發中是不存在的,iOS允許在View中再添加View,所以iOS中可以在一個UIScrollView中再添加一個UITableView。回到正題,看看如何解決Android開發中的這個問題,很簡單,在為ListView設定完adapter後,調用下面這個靜態方法就可以了:[java] public class Utility { public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { www.2cto.com // 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); www.2cto.com totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } }