Android 解决bug:异常提示"ListView cannot be cast to android.widget.BaseAdapter "
2015-10-21 19:16
597 查看
Android Bug:"ListView cannot be cast to android.widget.BaseAdapter "
文 | 莫若吻1.问题描述
在Android Studio中运行项目,测试项目中自定义的ListView控件功能时报常:java.lang.ClassCastException: com.baoyz.swipemenulistview.SwipeMenuListView$1 cannot be cast to android.widget.BaseAdapter
2.分析原因
个人遇到的情况总结出两种原因:1)一帮情况下自定义的ListView设置HeaderView、FooterVeiw很容易出现此异常。
如果在listview.setAdapter(adapter)方法之后添加头或尾view,即addHeaderView或 addFooterView,那么在你listView.removeHearderView或removeFooterView时会报该异常。
解决方法:一定要在setAdapter()之前调用addHeaderView()或addFooterVeiw()。
分析:ListView增加HeaderView之后,将原来的Adapter包装成HeaderViewListAdapter,看HeaderViewListAdapter的文档说明:
ListAdapter used when a ListView has header views. This ListAdapter wraps another one and also keeps track of the header views and their associated data objects.
This is intended as a base class; you will probably not need to use this class directly in your own code.
HeaderViewListAdapter有个方法getWrappedAdapter,该方法能返回被包装的HeaderViewListAdapter的ListAdapter。到了这里就明白为什么会报ClassCastException异常了。因为ListView的getAdapter方法返回的是HeaderViewListAdapter的实例,而将其转换成BaseAdapter的子类的实例,肯定是不对的。
2)在使用设置自定义ListView时,随意添加其属性,出现事件冲突,导致ListView出现异常,其中一项错误异常就是java.lang.ClassCastException: ListView cannot be cast to android.widget.BaseAdapter
比如:在布局的listview中设置了fastScrollEnabled属性,就会导致程序崩溃,出现此异常。
3.案例:
在项目中自定的ListView没有任何问题,在使用时的布局文件中给自定义的ListView添加一个属性fastScrollEnabled,运行程序后测试相关功能报异常:java.lang.ClassCastException: com.baoyz.swipemenulistview.SwipeMenuListView$1 cannot be cast to android.widget.BaseAdapter解决此类问题:删除该属性即可。
示例代码如图:
异常截图:
解决代码截图:
相关文章推荐
- 从源码中浅析Android中如何利用attrs和styles定义控件
- android.support.design.widget.TabLayout 用法解析
- Android 内存优化 (转载)
- Android 内存管理 &Memory Leak & OOM 分析
- Android ,TextView 设置onClick 没反应
- Anko for Android
- Android自定义控件之美观的实用型统计表的制作
- Android Studio中如何打JAR包
- 【转】Android截屏
- 【转】Android 音量键+电源键 截屏代码小结
- 【转】ANDROID LOLLIPOP SCREEN CAPTURE AND SHARING
- android之位置坐标
- [分享]4412开发板Android教程——Android开发环境搭建
- Android如何给无法更改继承关系的Activity更换ActionBar(setContentView方法实战)
- android studio moudle git 提交 没反应
- Android Camera HAL3中拍照Capture模式下多模块间的交互与帧Result与帧数据回调
- android EditText限制输入
- Android Fragment间对象传递
- Android studio 打jar包
- android 根据字母排序ListView item数据