先看下ListView的setAdapter方法里的部分代码:
/** * Sets the data behind this ListView. * * The adapter passed to this method may be wrapped by a {@link WrapperListAdapter}, * depending on the ListView features currently in use. For instance, adding * headers and/or footers will cause the adapter to be wrapped. * * @param adapter The ListAdapter which is responsible for maintaining the * data backing this list and for producing a view to represent an * item in that data set. * * @see #getAdapter() */ @Override public void setAdapter(ListAdapter adapter) { .......... if (mHeaderViewInfos.size() > 0|| mFooterViewInfos.size() > 0) { mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter); } else { mAdapter = adapter; } ......... }
再看removeFooterView的代码:
/** * Removes a previously-added footer view. * * @param v The view to remove * @return * true if the view was removed, false if the view was not a footer view */ public boolean removeFooterView(View v) { if (mFooterViewInfos.size() > 0) { boolean result = false; if (mAdapter != null && ((HeaderViewListAdapter) mAdapter).removeFooter(v)) { if (mDataSetObserver != null) { mDataSetObserver.onChanged(); } result = true; } removeFixedViewInfo(v, mFooterViewInfos); return result; } return false; }
看出点什么没,代码的大致意思是如果ListView没有headerView或者footerView的时候,与listView相关联的Adapter就是传进来的参数Adapter,如果有,就将原来的Adapter包装成HeaderViewListAdapter。
至此大致明白了自己错在哪里了,因为一开始第一页的时候用不到footerView,所以一开始创建的Adapter并不是HeaderViewListAdapter,然后在加载下一页的时候有添加和删除footerView的操作,但是当前的Adapter并不是HeaderViewListAdapter,导致错误发生,报了java.lang.ClassCastException错误。
明白了错误,也就有了相应的解决方案了。
先addHead或者addFooter再setAdapter就行。