问题描述
首先,我已经想通了,如何解决这个bug,但在这一点上我只是想知道为什么我的修补程序的工作。我跑成的情况是,我得到一个 ClassCastException异常,不能转换的LinearLayout $的LayoutParams到AbsListView $的LayoutParams
时,我试着做以下(简化为这些目的):
mLayout =(的LinearLayout)getLayoutInflater()
.inflate(R.layout.my_header_layout,
getListView(),FALSE);
mRootView.addView(mLayout);
。getListView()addHeaderView(mLayout);
getListView()setAdapter(mAdapter)。
我最终破裂下来,并发现,当我删除调用 mRootView.addView(mLayout)问题被固定
我的两方面问题是,为什么会出现这种情况?首先,在概念方面,那为什么当一个标题观点已经在整个事情刚刚去世的布局?是不是因为这种观点有效地试图进行布局两次:一次在头,一次用于实际的布局
?其次,为什么例外?这似乎非常非描述性的,它看起来并不像它在所有捕获的实际问题?这是不被处理,因为较低的水平功能将只是结果失败过高水平的问题的情况?
Your layout params are going crazy here, that's the problem.
inflate()
is called, assigningListView.LayoutParams
tomLayout
, since you pass a ListView as the root. From the docs:
When you use
addView()
, it checks the type of the child's params. If it doesn't match, it converts it as best it can. It does this by copying the values over in a new constructor. So, yourmLayout
now hasLinearLayout.LayoutParams
attached.Once you call
addHeaderView()
,mLayout
is now a child of the listview. One of the things done duringListView#setupChild()
is this:AbsListView.LayoutParams p = (AbsListView.LayoutParams) child.getLayoutParams();
This is almost definitely where you're getting the ClassCastException. You just can't do a straight cast like that.
It's not that bad, but you have to understand how the layout system works. Could they do a simple check, and just throw an error or log message if it's not right? Sure. Could ListView
try to gracefully handle the issue the way a LinearLayout
does? Sure. But they don't.
It might be worth posting on the Android Developer's forum/group/tracker if you think it could be handled better.
这篇关于设置的ListView头时抛出ClassCastException不能转换的LinearLayout $的LayoutParams到AbsListView $的LayoutParams的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!