Android:将标题视图添加到 ExpandableListView 时出现 ClassCastException [英] Android: ClassCastException when adding a header view to ExpandableListView

查看:36
本文介绍了Android:将标题视图添加到 ExpandableListView 时出现 ClassCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向 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));

这给了我以下错误:

 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)) 时发生的,但我不知道为什么.有什么想法吗?

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

推荐答案

好的,我想出了这个.我通过以编程方式将 View 的 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:

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

其中说明:

这些提供参数给此视图的 parent 指定它的排列方式.有许多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.

这篇关于Android:将标题视图添加到 ExpandableListView 时出现 ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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