zoukankan      html  css  js  c++  java
  • java.lang.IllegalStateException: Cannot add header view to list -- setAdapter has already been called.

    分析:android 4.2.X及以下的版本,addHeaderView必须在setAdapter之前,否则会抛出IllegalStateException。

    android 4.2.X(API 17) ListView源码如下:

    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();  
            }  
    }  
    

      

    android 4.3.X(API 18)ListView源码如下:

        public void addHeaderView(View v, Object data, boolean isSelectable) {
            ......
    
            // 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();
                }
            }
        }
    

    所以为了兼容android4.2.x及以下的版本,最好先addHeaderView,后setAdapter.

  • 相关阅读:
    记录一个jsonb_array_elements因数据问题被坑的点
    postgresql 中的 with 用法
    Java中4个元注解
    Java8 stream filter map
    sql 函数
    sql 判断选择语句
    面试里的套路(1)
    python 路径
    postsql sqlalchemy的事务提交问题
    网站响应过慢问题
  • 原文地址:https://www.cnblogs.com/ryq2014/p/5969499.html
Copyright © 2011-2022 走看看