1. 程式人生 > >ScrollView巢狀ListView,listItem.measure(0,0);報空指標異常NullPointerException

ScrollView巢狀ListView,listItem.measure(0,0);報空指標異常NullPointerException

1: SrollView巢狀ListView時顯示不全問題及ListView高度問題:
直接上程式碼,使用以下函式解決此問題:
    public void setListViewHeightOnChildren(ListView listView) {
        //adapter為ListView的介面卡
        if (adapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = adapter.getCount(); i < len; i++) {
            // 返回資料項的數目
            View listItem = adapter.getView(i, null, listView);
            // 子項View 的寬高
            listItem.measure(0, 0);
            // 計算所有子項的總高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 獲取子項間分隔符佔用的高度,adapter.getCount() == 1 ? 2 : adapter.getCount() - 1這個判斷是為了解決特殊情況(比如Item有設定MarginTop....),當只有一個Item時滑動出現顯示不全及被擷取一部分問題;
        params.height = totalHeight
                + (listView.getDividerHeight() * (adapter.getCount() == 1 ? 2
                        : adapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
2: 當呼叫listItem.measure(0, 0);報空指標時問題:
檢查Adapter適配時Item的根容器為RelativeLayout,
報錯原因:
In platform version 17 and lower, RelativeLayout was affected by a measurement bug that could cause child views to be measured with incorrect MeasureSpec values. (See MeasureSpec.makeMeasureSpec for more details.) This was triggered when a RelativeLayout container was placed in a scrolling container, such as a ScrollView or HorizontalScrollView. If a custom view not equipped to properly measure with the MeasureSpec mode UNSPECIFIED was placed in a RelativeLayout, this would silently work anyway as RelativeLayout would pass a very large AT_MOST MeasureSpec instead.
This behavior has been preserved for apps that set android:targetSdkVersion="17" or older in their manifest's uses-sdktag for compatibility. Apps targeting SDK version 18 or newer will receive the correct behavior
有三種解決方案:
一、升級版本到4.2.2
二、更改根容器為LinearLayout
三、在介面卡裡新增convertView.setLayoutParams(new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); convertView為Item的view