android ListView分页出现java.lang.ClassCastException

在listView分页中,当刷下一页的数据时,会出现java.lang.ClassCastException: android.widget.HeaderViewListAdapter 不能强转为listview的异常信息,这是因为当向listview中加入headerview或者footviwer时,调用ListView的setAdapter方法会将adapter转化为headerviewlistadapter,如下源代码所示:

ListView.setAdapter源代码:

 public void setAdapter(ListAdapter adapter) {
        if (null != mAdapter) {
            mAdapter.unregisterDataSetObserver(mDataSetObserver);
        }

        resetList();
        mRecycler.clear();

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

        mOldSelectedPosition = INVALID_POSITION;
        mOldSelectedRowId = INVALID_ROW_ID;
        if (mAdapter != null) {
            mAreAllItemsSelectable = mAdapter.areAllItemsEnabled();
            mOldItemCount = mItemCount;
            mItemCount = mAdapter.getCount();
            checkFocus();

            mDataSetObserver = new AdapterDataSetObserver();
            mAdapter.registerDataSetObserver(mDataSetObserver);

            mRecycler.setViewTypeCount(mAdapter.getViewTypeCount());

            int position;
            if (mStackFromBottom) {
                position = lookForSelectablePosition(mItemCount - 1, false);
            } else {
                position = lookForSelectablePosition(0, true);
            }
            setSelectedPositionInt(position);
            setNextSelectedPositionInt(position);

            if (mItemCount == 0) {
                // Nothing selected
                checkSelectionChanged();
            }

            if (mChoiceMode != CHOICE_MODE_NONE &&
                    mAdapter.hasStableIds() &&
                    mCheckedIdStates == null) {
                mCheckedIdStates = new LongSparseArray<Boolean>();
            }

        } else {
            mAreAllItemsSelectable = true;
            checkFocus();
            // Nothing selected
            checkSelectionChanged();
        }

        if (mCheckStates != null) {
            mCheckStates.clear();
        }
        
        if (mCheckedIdStates != null) {
            mCheckedIdStates.clear();
        }

        requestLayout();
    }

 上面红色字即为原因所在

解决方法:

HeaderViewListAdapter  listAdapter = (HeaderViewListAdapter) ListView.getAdapter();
MyAdapter adapter = (WblistAdapter)listAdapter.getWrappedAdapter();

上述代码即可转为我们自定义的adapter

你可能感兴趣的:(ListView)