ScrollView中的ListView在大于18的android API上完美运行,但是比API 18更低的应用程序崩溃显示行中的java.lang.NullPointerException MyUtils.java上的 listItem.measure(0,0);
MyUtils.java
public static void setListViewHeightBasedOnChildren(ExpandableListView 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));
listView.setLayoutParams(params);
listView.requestLayout();
}
fragment_list.xml
<FrameLayout 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"
tools:context="sportsnewsforcrazysportpepllatestnewsjstwaao.com.sportsnews.fragments.Frag_List">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/networkImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="@color/divider"
android:minHeight="150dp"/>
<ExpandableListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/expandableListView"
android:scrollbars="none"
android:background="@color/app_background"
android:childDivider="@color/app_background"/>
</LinearLayout>
</ScrollView>
Fragment_list.java
adapter = new ExpandableListViewAdapter(getActivity() , dataList);
expandableListView.setAdapter(adapter);
MyUtils.setListViewHeightBasedOnChildren(expandableListView);
expandableListView.setOnGroupClickListener(this);
expandableListView.setOnChildClickListener(this);
答案 0 :(得分:0)
在我的应用中,如果listview项目布局的根视图是RelativeLayout,则会导致此崩溃。因为在api 18 RelativeLayout源代码中
if(mLayoutParams.width >= 0) {
width = Math.max(width, mLayoutParams.width);
}
并在api&gt; = 19 RelativeLayout源代码
if(mLayoutParams != null && mLayoutParams.width >= 0) {
width = Math.max(width, mLayoutParams.width);
}
如果您在此方法中夸大项目视图,则mLayoutParams可能为null:
contentView = (ViewGroup) LayoutInflater.
rom(context).inflate(R.layout.select_text_oprate_window, null);
所以,你可以使用这个方法:
contentView = (ViewGroup)
LayoutInflater.from(context).inflate(R.layout.select_text_oprate_window, parent,false);
您还可以将项目布局的根视图更改为LinearLayout。