Android fragments scrollview中的listview不适用于低于API 18的android版本
ScrollView内部的ListView在大于18的android API上运行良好,但低于API 18的应用程序崩溃显示java.lang.NullPointerException在第行 listItem.measure(0,0)在MyUtils.java上 MyUtils.javaAndroid fragments scrollview中的listview不适用于低于API 18的android版本,android-fragments,android-listview,scrollview,expandablelistview,Android Fragments,Android Listview,Scrollview,Expandablelistview,ScrollView内部的ListView在大于18的android API上运行良好,但低于API 18的应用程序崩溃显示java.lang.NullPointerException在第行 listItem.measure(0,0)在MyUtils.java上 MyUtils.java public static void setListViewHeightBasedOnChildren(ExpandableListView listView) { ListAdapt
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();
}
adapter = new ExpandableListViewAdapter(getActivity() , dataList);
expandableListView.setAdapter(adapter);
MyUtils.setListViewHeightBasedOnChildren(expandableListView);
expandableListView.setOnGroupClickListener(this);
expandableListView.setOnChildClickListener(this);
在我的应用程序中,如果listview项布局的根视图是RelativeLayout,则会导致此崩溃
if(mLayoutParams.width>=0){
宽度=数学最大值(宽度,mLayoutParams.width);
}
并且在api>=19的源代码中
if(mLayoutParams!=null&&mLayoutParams.width>=0){
宽度=数学最大值(宽度,mLayoutParams.width);
}
如果使用此方法膨胀项目视图,mLayoutParams可能为空:
contentView=(视图组)布局展开器。
rom(上下文)。充气(R.layout.select\u text\u oprate\u window,空)代码>
因此,您可以使用以下方法:
contentView=(视图组)
LayoutFlater.from(上下文)。充气(R.layout.select\u text\u oprate\u window,parent,false)代码>
您还可以将项目布局的根视图更改为LinearLayout。因为嵌套的可滚动视图在更高的API级别之前不受支持。最好还是避免嵌套可滚动的视图
。不管你的布局看起来如何,总有一条路可以绕过它。谢谢你的回答@Xaver。我知道避免嵌套可滚动视图是个好主意,但在某些情况下,我们需要它,因为我在问。还有一件事,请不要介意,但上面的答案并不是问题的正确答案。我在之前的评论中试图指出的一点是,它从来都不是真正需要的。对于较低的API,有一些变通方法可以使嵌套滚动工作,但它们都有自己的缺点。如果您想正确地实现这一点,那么不要嵌套两个可滚动视图。您只需使用一个可滚动的视图
即可实现相同的功能。如果出于任何原因,我真的必须嵌套两个可滚动的视图
,那么为什么不使用支持库中的RecyclerView
或NestedScrollView
,将嵌套的滚动行为向后移植到较旧的API?哦,是的,RecyclerView是最好的主意。。谢谢@Xaver
adapter = new ExpandableListViewAdapter(getActivity() , dataList);
expandableListView.setAdapter(adapter);
MyUtils.setListViewHeightBasedOnChildren(expandableListView);
expandableListView.setOnGroupClickListener(this);
expandableListView.setOnChildClickListener(this);