关于android开发的异常

关于android开发使用onContextItemSelected方法的异常处理

错误代码 :android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
报错如下截图:
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
错误原因如下图所示:

在这里插入图片描述
因为在项目使用了onContextItemSelected方法,return返回使用了默认super父类方法super.onContextItemSelected(item),所以导致报错:

android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

解决办法

方法1:修改return默认值true
在这里插入图片描述

方法2:把switch的break中断改为return true,结束switch语句并且跳出当前函数,不在执行后面的语句。
在这里插入图片描述

原理是super.onContextItemSelected(item)默认返回是false,表示交给系统自己处理该事件,此时系统会调用ComtextImpl.startActivity()方法,所以就报错了。
方法文档地址:[link]https://developer.android.com/reference/android/app/Activity#onContextItemSelected(android.view.MenuItem)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值