android:classcastException添加标头视图以explabableStview
-
10-10-2019 - |
题
我正在尝试将标题添加到ExplablelistView这样的标题:
headerView = View.inflate(this, R.layout.header, null);
expandableListView.addHeaderView(headerView);
expandableListView.setAdapter(new SectionedAdapter(this));
这给了我以下错误:
12-08 16:23:42.354:
ERROR/AndroidRuntime(421): Caused by:java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams
12-08 16:23:42.354: ERROR/AndroidRuntime(421): at android.widget.ListView.clearRecycledState(ListView.java:504)
12-08 16:23:42.354: ERROR/AndroidRuntime(421): at android.widget.ListView.resetList(ListView.java:490)
12-08 16:23:42.354:ERROR/AndroidRuntime(421):at android.widget.ListView.setAdapter(ListView.java:422)
12-08 16:23:42.354:ERROR/AndroidRuntime(421): at android.widget.ExpandableListView.setAdapter(ExpandableListView.java:475)
这是在呼吁 expandableListView.setAdapter(new SectionedAdapter(this))
, ,但我不知道为什么。有任何想法吗?
解决方案
好的,我想出了这个。我通过编程将视图的LayoutParams设置为ListView LayoutParams,从而摆脱了运行时错误,例如:
headerView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.FILL_PARENT, ListView.LayoutParams.WRAP_CONTENT));
在添加视图之前。出现在Android文档中的原因:
哪个指出:
这些供应参数 父母 在该观点中指定了应该如何布置。 ViewGroup.layoutparams有许多子类,这些子类对应于负责安排子女的ViewGroup的不同子类。
因此,基本上,如果要将视图添加到另一个视图,则必须将视图的LayoutParams设置为父母使用的LayoutParams类型,否则您将获得运行时错误。
其他提示
即使以上答案可能对许多人有用,但仍然有更好的解释。ClassCastException
打电话后的正常行为 listview.addHeaderView
或者 listview.addFooterView
.
原因是初始适配器包裹在 HeaderViewListAdapter
. 。要获得适配器,请使用此代码。
YourAdapter ya = (YourAdapter) ((HeaderViewListAdapter)lv.getAdapter()).getWrappedAdapter();
就我而言,这不起作用。在设置适配器之前,我不得不将脚户列入我的listView。首先,我从onCreate方法中的布局文件初始化了我的加载视图:
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
loadingView = layoutInflater.inflate(R.layout.loading_view, null);
然后,我以相同的方法使用了此解决方法:
this.setIsLoading(true);
listView.setAdapter(adapter);
this.setIsLoading(false);
在哪里
private void setIsLoading(boolean isLoading)
{
this.isLoading = isLoading;
if (isLoading) {
listView.addFooterView(loadingView);
}
else {
listView.removeFooterView(loadingView);
}
}
您应该将父母的视图放在膨胀的视图中。
ListView listview = (ListView) findViewById(R.id.listview);
headerView = View.inflate(this, R.layout.header, listview, false); // set listview as parent view
listview.addHeaderView(headerview);
不隶属于 StackOverflow