Cannot add header view to list setAdapter has already been called

原来没有注意,有些机子会报这个错误,
经过查询,

//对于其listview的回收,需要使用如下方式:
//在activity的onstart生命状态中执行重建操作:
listview.addHeaderView(View);
listview.addFooterView(View);
listview.setAdapter(Adapter);
//在Activity的onstop生命状态中执行销毁操作:
listview.removeHeaderView(View);
listview.removeFooterView(View);
listview.setAdapter(null);

对于包含headerview和footerview的listview,在listview.setAdapter(null);调用之前,必须要进行listview.removeHeaderView()和listview.removeFooterView()操作,这样才能将listview的绑定adapter对象置空。否则,在调用listview.getAdapter()的返回值不为null(
不为null的原因是,在存在headerview或者footerview后,调用listview.setAdapter(null)操作时,在源码中会存在Adapter类型转换,如图:

if (mHeaderViewInfos.size() > 0|| mFooterViewInfos.size() > 0) { mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter); } else { mAdapter = adapter; }  

会将Adapter对象指向HeaderViewListAdapter的新对象 –> new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, null)。

参考:http://blog.csdn.net/liguangzhenghi/article/details/48543481

你可能感兴趣的:(Cannot add header view to list setAdapter has already been called)