onListItemClick 中的 Android SwitchCase

标签 android listview switch-statement

我正在尝试使用开关盒。但它说我不能传递一个字符串:(

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/

相关文章:

c# - 在交换机中使用 'goto'?

java - 应用程序 IncomingHandler 有时收不到服务消息

java - 什么时候将 Activity 传递给另一个类会导致内存泄漏?

Android Listview - GetView 将更改应用于我不想要的项目

android - 显示一个List的所有产品

javascript - 如何避免输入值切换大小写

Android:仅获取根布局的屏幕尺寸

android - Eclipse 安卓错误

android - 无法从总数中减去 SharedPreference 编号

c++ - 为什么即使我使用 [[fallthrough]],GCC 也会警告我失败?