在枚举中使用字符串资源并在switch case中使用

时间:2016-08-25 17:23:31

标签: java android

我有一个要求,我必须使用android中的资源字符串来支持不同的语言。 Switch case不会将字符串作为常量从资源中获取。 与R.string.example一样

所以我必须使用enums.Need一个例子在android中使用字符串资源使用枚举常量并在Switch case中使用它

1 个答案:

答案 0 :(得分:1)

enums是userdefine常量,因此您无法将它们与资源进行比较(您可以将它们分配给枚举并使用相等的函数与String resourece值进行比较),这是一种冗长的避免它。

你可以使用带有java 1.7+的开关的字符串虽然android管理xml中每个资源的唯一int id,所以你可以将你的开关案例字符串输入添加到资源' strings.xml'并使用像int

switch (stringResourceID) {
case R.string.first_string:
     break;
case R.string.second_string:
     break;
case R.string.third_string:
     break;
default:
     break;
}

您还可以使用' public static final string'并使用它们作为案例标签,你应该在一个单独的文件中声明这样的常量,以使它们易于访问

public static final String C1="first";
public static final String C2="second";
public static final String C3="third";


    switch (yourInputString) {
    case C1:
         break;
    case C2:
         break;
    case C3:
         break;
    default:
         break;
    }

example

相关问题