在開發的過程當中,由於手機屏幕的大小的限制,我們經常需要使用滑動的方式,來顯示更多的內容。在最近的工作中,遇見一個需求,需要將ListView嵌套到ScrollView中顯示。於是乎有了如下布局:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#FFE1FF"
- android:orientation="vertical" >
- <ScrollView
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <ListView
- android:id="@+id/listView1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:fadingEdge="vertical"
- android:fadingEdgeLength="5dp" />
- </LinearLayout>
- </ScrollView>
- </LinearLayout>
運行程序,如下結果,無論你如何調整layout_width,layout_height屬性,ListView列表只顯示一列!

在查閱的各種文檔和資料后,發現在ScrollView中嵌套ListView空間,無法正確的計算ListView的大小,故可以通過代碼,根據當前的ListView的列表項計算列表的尺寸。實現代碼如下:
- public class MainActivity extends Activity {
- private ListView listView;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- listView = (ListView) findViewById(R.id.listView1);
- String[] adapterData = new String[] { "Afghanistan", "Albania",… … "Bosnia"};
- listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,adapterData));
- setListViewHeightBasedOnChildren(listView);
- }
- public void setListViewHeightBasedOnChildren(ListView listView) {
- // 獲取ListView對應的Adapter
- ListAdapter listAdapter = listView.getAdapter();
- if (listAdapter == null) {
- return;
- }
- int totalHeight = 0;
- for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
- // listAdapter.getCount()返回數據項的數目
- View listItem = listAdapter.getView(i, null, listView);
- // 計算子項View 的寬高
- listItem.measure(0, 0);
- // 統計所有子項的總高度
- totalHeight += listItem.getMeasuredHeight();
- }
- ViewGroup.LayoutParams params = listView.getLayoutParams();
- params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
- // listView.getDividerHeight()獲取子項間分隔符占用的高度
- // params.height最后得到整個ListView完整顯示需要的高度
- listView.setLayoutParams(params);
- }
- }