最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

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

Android crifan 6354浏览 0评论

【问题】

折腾:

【记录】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

去试试,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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.所以再去改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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); 
    }
};

就可以了。

 

【总结】

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

转载请注明:在路上 » 【已解决】android中switch中的case中不用使用enum枚举值:Type mismatch: cannot convert from xxx to int

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (1)

  1. java中switch_case的每一项必须为能够隐式转换为int类型的常量,如byte、short、char、int。java7之后才增加String类型
    游客11年前 (2014-09-17)回复
86 queries in 0.468 seconds, using 22.19MB memory