44

我正在尝试向 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)),但我不知道为什么。有任何想法吗?

4

4 回答 4

91

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

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

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

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

其中指出:

这些向该视图的父级提供参数, 指定它应该如何排列。ViewGroup.LayoutParams 有很多子类,它们对应着不同的 ViewGroup 子类,它们负责安排他们的子类。

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

于 2010-12-09T17:43:50.887 回答
5

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

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

YourAdapter ya = (YourAdapter) ((HeaderViewListAdapter)lv.getAdapter()).getWrappedAdapter();

从这里获取的代码

于 2014-11-03T18:20:46.197 回答
1

就我而言,这不起作用。在设置它的适配器之前,我必须为我的 listView 设置一个 footerView。首先,我从 OnCreate 方法中的布局文件初始化了 loadingView:

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);
    }
}
于 2013-11-28T17:39:26.780 回答
0

你应该把父视图放到你的膨胀视图中。

ListView listview = (ListView) findViewById(R.id.listview);
headerView = View.inflate(this, R.layout.header, listview, false); // set listview as parent view
listview.addHeaderView(headerview);
于 2017-03-16T01:56:08.867 回答