Android 解决bug:异常提示"ListView cannot be cast to android.widget.BaseAdapter "


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

解决此类问题:删除该属性即可。

示例代码如图:











异常截图:



解决代码截图:




  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值