ScrollView 嵌套 ListView or ExpandableListView顯示問題(一行屬性搞定)

前言

開發項目的過程中某些複雜UI界面難免會用到滾動視圖嵌套列表視圖的情況

ScrollView 使用場景

若一個手機屏幕的大小都不能夠顯示整個頁面的話,最外層根視圖可以考慮使用ScrollView

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

</ScrollView>

當然,使用ScrollView也會有一個侷限性。 相信大家應該也都瞭解到 ScrollView 的子佈局只允許有一個,否則XML的編譯也會報錯。

這裏寫圖片描述

ScrollView嵌套列表出現的問題

這是一個根視圖爲ScrollView 的XML佈局,裏面嵌套的是ListView。然後就會出現列表內容只顯示了一個Item。就算有多組數據,列表也只會顯示一個。

這裏寫圖片描述

根據以往的經驗,可能會想到去動態的計算出每一個Item的寬高纔可以完全顯示,這也算是一種辦法。但是沒辦法在Preview中查看ListView是否真的顯示完整,只能通過運行到模擬器或者真機上調試看效果。
動態計算每一個Item的代碼:

public static void setListViewHeightBasedOnChildren(ExpandableListView listView) {
        //獲取ListView對應的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {   //listAdapter.getCount()返回數據項的數目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);  //計算子項View 的寬高
            totalHeight += listItem.getMeasuredHeight();  //統計所有子項的總高度
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        //listView.getDividerHeight()獲取子項間分隔符佔用的高度
        //params.height最後得到整個ListView完整顯示需要的高度
        listView.setLayoutParams(params);
}

這並不是我們最終想要的效果。
其實只要在根視圖中加一行 android:fillViewport="true" 就可以了。 不管內部嵌套的是ListView 還是ExpandableListView 都能完美解決這個問題。

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">
     <ListView
            android:id="@+id/listview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
</ScrollView>

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章