listItem.measure(0, 0) 空指針問題

在android中有時候scrollView須要嵌套listview,當scrollView嵌套listview時,會出現listview顯示不全的問題,這時候有不少解決的辦法,其中一個相似下面的代碼:android

public void setListViewHeightBasedOnChildren(ListView listView) {  ide

        ListAdapter listAdapter = listView.getAdapter();   佈局

        if (listAdapter == null) {  spa

            return;  指針

        }  ci

        int totalHeight = 0;  get

        for (int i = 0; i < listAdapter.getCount(); i++) {  it

            View listItem = listAdapter.getView(i, null, listView);  容器

            listItem.measure(0, 0);  sed

            totalHeight += listItem.getMeasuredHeight();  

        }  

        ViewGroup.LayoutParams params = listView.getLayoutParams();  

        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() -1));  

        listView.setLayoutParams(params);  

        scrollview.scrollTo(0, 0);

    }

可是有時候listItem.measure(0, 0)會平白無故的報空指針異常,緣由就是你的listview的item佈局中的最底層的layout不是LinearLayout,可能用了RelativeLayout,但RelativeLayout中沒有重寫onmeasure方法,因此報了空指針異常,這時候把根容器改成LinearLayout就行了

相關文章
相關標籤/搜索