【已解决】android中switch中的case中不用使用enum枚举值:Type mismatch: cannot convert from xxx to int

【问题】

折腾:

【记录】Android中创建进程或线程去实现USB设备插入的状态检测

期间,定义了个枚举。

然后打算在switch的case中使用,结果出错:

Type mismatch: cannot convert from DeviceListActivity.usb_action to int

如图:

Type mismatch cannot convert from DeviceListActivity.usb_action to int

【解决过程】

1.参考:

Java using enum with switch statement

去试试,

	public enum usb_action{
		USB_ACTION_UNKNOWN,
		USB_ACTION_ATTACH,
		USB_ACTION_DETACH,
	};
	
    public Handler mHandler=new Handler()  
    {  
        public void handleMessage(Message msg)  
        {
        	usb_action curUsbAction = usb_action.values()[msg.what]; //do your own bounds checking
            switch(curUsbAction)  
            {
            case usb_action.USB_ACTION_UNKNOWN:
                //do sth.
                break;  
            default:  
                break;        
            }  
            super.handleMessage(msg);  
        }  
    };  

结果还是出错:

The qualified case label DeviceListActivity.usb_action.USB_ACTION_UNKNOWN must be replaced with the unqualified enum constant USB_ACTION_UNKNOWN

如图:

The qualified case label must be replaced with the unqualified enum constant

2.所以再去改为:

	public enum usb_action{
		USB_ACTION_UNKNOWN,
		USB_ACTION_ATTACH,
		USB_ACTION_DETACH,
	};
	
    public Handler mHandler=new Handler()  
    {  
        public void handleMessage(Message msg)  
        {
        	usb_action curUsbAction = usb_action.values()[msg.what]; //do your own bounds checking
            switch(curUsbAction)  
            {
            case USB_ACTION_UNKNOWN:
                //do sth.
                break;  
            default:  
                break;        
            }  
            super.handleMessage(msg);  
        }
    };

就可以了。

 

【总结】

如上图,使用类似于这样的写法:

	public enum usb_action{
		USB_ACTION_UNKNOWN,
		USB_ACTION_ATTACH,
		USB_ACTION_DETACH,
	};
	
    public Handler mHandler=new Handler()  
    {  
        public void handleMessage(Message msg)  
        {
        	usb_action curUsbAction = usb_action.values()[msg.what]; //do your own bounds checking
            switch(curUsbAction)  
            {
            case USB_ACTION_UNKNOWN:
                //do sth.
                break;  
            default:  
                break;        
            }  
            super.handleMessage(msg);  
        }
    };

就可以了。

注:

暂时不知道:

case xxx;

中的xxx,为何写成:

usb_action.USB_ACTION_UNKNOWN

会出错,而必须写成:

USB_ACTION_UNKNOWN



One Thought on “【已解决】android中switch中的case中不用使用enum枚举值:Type mismatch: cannot convert from xxx to int

  1. java中switch_case的每一项必须为能够隐式转换为int类型的常量,如byte、short、char、int。java7之后才增加String类型

发表评论

电子邮件地址不会被公开。 必填项已用*标注

无觅相关文章插件,快速提升流量