Exception prompt: Java. Lang. illegalstateexception: cannot add header view to list -- setadapter has already been called.
Cause: addheaderview () is called after setadapter (), and the code runs in the system version before android4.3. Table of Android SDK and API level
Let's take a look at the listview code snippets of the (android4.3) API-18 and (android4.2) API-17:
API-18
public void addHeaderView(View v, Object data, boolean isSelectable) { final FixedViewInfo info = new FixedViewInfo(); info.view = v; info.data = data; info.isSelectable = isSelectable; mHeaderViewInfos.add(info); // Wrap the adapter if it wasn't already wrapped. if (mAdapter != null) { if (!(mAdapter instanceof HeaderViewListAdapter)) { mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, mAdapter); } // In the case of re-adding a header view, or adding one later on, // we need to notify the observer. if (mDataSetObserver != null) { mDataSetObserver.onChanged(); } }}
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 = data; info.isSelectable = isSelectable; mHeaderViewInfos.add(info); // in the case of re-adding a header view, or adding one later on, // we need to notify the observer if (mAdapter != null && mDataSetObserver != null) { mDataSetObserver.onChanged(); }}
In the API-17, if the adapter is not empty, it will directly throw an exception, and in the API-18 is related to the optimization.
Suggestions
We have a constructive proposal and can only remind you that the mainstream Android system on the market is still versions earlier than android4.3. Therefore, pay attention to this when using addheaderview.