安卓:ClassCastException异常增加一个头,以ExpandableListView时 [英] Android: ClassCastException when adding a header view to ExpandableListView

查看:413
本文介绍了安卓:ClassCastException异常增加一个头,以ExpandableListView时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个头添加到ExpandableListView像这样:

I'm trying to add a header to an ExpandableListView like so:

headerView = View.inflate(this, R.layout.header, null);
expandableListView.addHeaderView(headerView);
expandableListView.setAdapter(new SectionedAdapter(this));

这使我有以下错误:

Which gives me the following error:

 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(新SectionedAdapter(本)),但我想不出为什么。任何想法?

This is happening at the call to expandableListView.setAdapter(new SectionedAdapter(this)), but I can't figure out why. Any ideas?

推荐答案

好吧,我想通这一个。我得到了通过编程设置视图的的LayoutParams到ListView控件的LayoutParams,像这样摆脱了运行时错误的:

Ok, I figured this one out. I got rid of the runtime error by programatically setting the View's LayoutParams to ListView LayoutParams, like so:

headerView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.FILL_PARENT, ListView.LayoutParams.WRAP_CONTENT));

添加视图之前。是的原因是在Android文档中:

before adding the view. The reason being is found in the Android docs:

<一个href="http://developer.android.com/reference/android/view/View.html#setLayoutParams%28android.view.ViewGroup.LayoutParams%29">http://developer.android.com/reference/android/view/View.html#setLayoutParams(android.view.ViewGroup.LayoutParams)

其中指出:

这些电源参数到   的这个观点指明应如何安排的。有许多   ViewGroup.LayoutParams的子类,   与这些对应于不同   ViewGroup中的那些子   负责安排他们的   孩子。

These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.

因此​​,基本上,如果你添加一个视图到另一个,则必须将欣赏到的LayoutParams的的LayoutParams键入父使用,否则你会得到一个运行时错误。

So basically, if you are adding a view to another, you MUST set the LayoutParams of the view to the LayoutParams type that the parent uses, or you will get a runtime error.

这篇关于安卓:ClassCastException异常增加一个头,以ExpandableListView时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆