Using string from resource XML in Switch?

白昼怎懂夜的黑 提交于 2019-12-10 12:37:55

问题


New to Android here, so I apologize if this is a simplistic question.

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".

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!

Thanks :)


回答1:


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.

EDIT: String switch statements are supported if you use JDK 1.7 and later

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;
}



回答2:


Well, it's not the most elegant way, but you can use if - else if statements instead of switch - case:

if (myStringVariable.equals(getString(R.string.first_string))) {
    // do something
} else if (myStringVariable.equals(getString(R.string.second_string))) {
    // do something
} else if (myStringVariable.equals(getString(R.string.third_string))) {
    // do something
}



回答3:


You're not missing something Android-related but Java-related instead.

Check this answer about how Java manages the Switch statement:

https://stackoverflow.com/a/3827424/2823516

You'll have to use the non elegant solution you mentioned. But who says is not elegant? Is what you should do, and that makes it elegant.



来源:https://stackoverflow.com/questions/29541914/using-string-from-resource-xml-in-switch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!