在Switch中使用来自资源XML的字符串? [英] Using string from resource XML in Switch?
问题描述
这里是Android的新功能,如果这是一个简单的问题,我深表歉意.
New to Android here, so I apologize if this is a simplistic question.
我正在尝试使用基于XML中字符串资源的开关.看起来像这样:
I am attempting to use a switch based on string resources in my XML. It would look something like this:
switch (myStringVariable) {
case getResources().getString(R.string.first_string):
break;
case getResources().getString(R.string.second_string):
break;
case getResources().getString(R.string.third_string):
break;
default:
break;
}
不幸的是,这行不通.我得到的错误是需要常量表达式".
Unfortunately, this won't work. The error that I get is "Constant expression required".
是否有一种半优雅的方法来执行此操作,而不必执行诸如创建3个String对象并将字符串资源分配给每个对象的操作?我觉得我缺少明显的东西,所以任何帮助都会很棒!
Is there a semi-elegant way to go about this, without having to do something like create 3 String objects and assign the string resources to each object? I feel like I'm missing something obvious, so any assistance would be great!
谢谢:)
推荐答案
首先,Android所基于的Java版本不支持String开关语句,因此通常必须使用if/else
块代替
Well, first of all, the version of Java that Android is based on does not support String switch statements, so generally you have to use if/else
blocks instead.
编辑:如果您使用的是JDK 1.7和更高版本,则支持字符串切换语句.
String switch statements are supported if you use JDK 1.7 and later
我不确定您的用例是什么,但是如果您的资源ID为myStringVariable
(即int
),则可以进行切换:
I'm not sure what your use case is, but if you have the resource ID of myStringVariable
, which is an int
, you can do a switch over that:
switch (myStringResId) {
case R.string.first_string:
break;
case R.string.second_string:
break;
case R.string.third_string:
break;
default:
break;
}
这篇关于在Switch中使用来自资源XML的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!