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 :)
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
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With