Android:向ExpandableListView添加标题视图时的ClassCastException

Chr*_*rry 44 android classcastexception expandablelistview android-linearlayout

我正在尝试向ExpandableListView添加标头,如下所示:

headerView = View.inflate(this, R.layout.header, null);
expandableListView.addHeaderView(headerView);
expandableListView.setAdapter(new SectionedAdapter(this));
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

 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)
Run Code Online (Sandbox Code Playgroud)

这是在电话会议上发生的expandableListView.setAdapter(new SectionedAdapter(this)),但我无法弄清楚原因.有任何想法吗?

Chr*_*rry 91

好的,我想出了这个.我通过以编程方式将View的LayoutParams设置为ListView LayoutParams来消除运行时错误,如下所示:

headerView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.FILL_PARENT, ListView.LayoutParams.WRAP_CONTENT));
Run Code Online (Sandbox Code Playgroud)

在添加视图之前.原因可以在Android文档中找到:

http://developer.android.com/reference/android/view/View.html#setLayoutParams(android.view.ViewGroup.LayoutParams)

其中指出:

这些供应参数指向此视图的 父级,指定应如何排列.ViewGroup.LayoutParams有许多子类,它们对应于负责安排子节点的ViewGroup的不同子类.

所以基本上,如果要将视图添加到另一个视图,则必须将视图的LayoutParams设置为父级使用的LayoutParams类型,否则您将收到运行时错误.

  • 我花了最后两个小时试图找出这个.谢谢! (3认同)
  • +1花时间来解释这个问题.没有人有一个非常好的答案 (2认同)

Ade*_*mad 5

尽管上述答案可能适用于许多人,但仍有更好的解释。 ClassCastException是调用listview.addHeaderViewor后的正常行为listview.addFooterView

原因是初始适配器被包裹在HeaderViewListAdapter. 要获取您的适配器,请使用此代码。

YourAdapter ya = (YourAdapter) ((HeaderViewListAdapter)lv.getAdapter()).getWrappedAdapter();
Run Code Online (Sandbox Code Playgroud)

代码取自这里