我正在尝试使用开关盒。但它说我不能传递一个字符串:(
protected void onListItemClick(ListView l, View v, int position, long id) {
// super.onListItemClick(l, v, position, id);
String selection = l.getItemAtPosition(position).toString();
Log.i("Harsha", selection);
switch (selection) {
case "Compose":
break;
case "Inbox":
break;
case "Drafts":
break;
case "Sent":
break;
default:
break;
}
}
错误是
Cannot switch on a value of type String. Only convertible int values or enum constants are permitted
最佳答案
The switch expression must be of type char, byte, short, or int. All case labels must be constant expressions—the expressions must contain only literals or named constants initialized with constant expressions—and must be assignable to the type of the switch expression.
就是这样! Java 不允许您将 String 传递给 switch case 语句,事实上,新提案可能已被拒绝。 (在某个地方的博客上读到,对不起,没有来源)
但这并不意味着你不能用其他方法来做。
备选方案
1) 使用列表项的位置,而不是字符串。
2) 使用Enum
3) 将其存储在 Map<String,Integer>
中(甚至一个数组),并在 SWitch Case 中使用 Value
编辑:就我个人而言,我会添加 4 个常量并以这种方式进行
final int MENU_COMPOSE = 0; //should be equal to the index in your array.
final int MENU_INBOX = 1;
final int MENU_DRAFTS = 2;
final int MENU_SENT = 3;
switch (position) {
case MENU_COMPOSE: //Compose, add comments never the less.
break;
case MENU_INBOX: //Inbox
break;
case MENU_DRAFTS: //Drafts
break;
case MENU_SENT: //Sent
break;
default:
break;
}
关于onListItemClick 中的 Android SwitchCase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4533633/