解決ScrollView中ListView嵌套問題

解決ScrollView中ListView嵌套問題 和 listview顯示不全問題   。  查了好多大牛的解決方式,這種辦法比較好,親測可用。

注意setListViewHeightBaseOnChildren 放的位置,必須在listview.setAdapter()之後。

佈局文件代碼:

<ScrollView
    android:fillViewport="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:dividerHeight="0.0dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>

</ScrollView>
java代碼類:

public class Utility {

    /**
     * 解決ScrollViewListView嵌套問題
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {  
            // 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);  
            totalHeight += listItem.getMeasuredHeight();  
        }  
  
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1) + 95);  
									//95爲: 解決listview顯示不全問題
        listView.setLayoutParams(params);  
    }  
} 



發佈了30 篇原創文章 · 獲贊 29 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章