gpt4 book ai didi

Android:将标题 View 添加到 ExpandableListView 时出现 ClassCastException

转载 作者:IT王子 更新时间:2023-10-28 23:51:59 24 4
gpt4 key购买 nike

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

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

最佳答案

好的,我想通了。通过以编程方式将 View 的 LayoutParams 设置为 ListView LayoutParams,我摆脱了运行时错误,如下所示:

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

在添加 View 之前。原因可在 Android 文档中找到:

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

其中指出:

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.

因此,基本上,如果您要向另一个 View 添加 View ,则必须将 View 的 LayoutParams 设置为父级使用的 LayoutParams 类型,否则会出现运行时错误。

关于Android:将标题 View 添加到 ExpandableListView 时出现 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4393775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com