首页 > 代码库 > addHeaderView()异常 —— setAdapter has already been called

addHeaderView()异常 —— setAdapter has already been called

异常提示:java.lang.IllegalStateException: Cannot add header view to list -- setAdapter has already been called.

产生原因:addHeaderView()调用在setAdapter()之后,并且该代码运行在Android4.3之前的系统版本。Android SDKAPI Level对应表

 

我们来看看(Android4.3API-18 和 (Android4.2API-17Listview代码片段:

API-18   

public void addHeaderView(View v, Object data, boolean isSelectable) {
        final FixedViewInfo info = new FixedViewInfo();
        info.view = v;
        info.data = http://www.mamicode.com/data;>

API-17

public void addHeaderView(View v, Object data, boolean isSelectable) {
 
        if (mAdapter != null && ! (mAdapter instanceof HeaderViewListAdapter)) {
            throw new IllegalStateException(
                    "Cannot add header view to list -- setAdapter has already been called.");
        }
 
        FixedViewInfo info = new FixedViewInfo();
        info.view = v;
        info.data = http://www.mamicode.com/data;>


API-17中,假如adapter不为空,则会直接抛出异常,而在API-18中则做了相关的优化。

建议

木有建设性的提议,只能提醒大家,目前市面上主流的Android系统还是Android4.3以下版本,所以在使用addHeaderView()要注意这一点。