Reputation: 1003
I have a "numeric.xml" file in my project's "values" directory that holds most of the project's integer constants. I would like to use some of those constants in a switch statement, but Eclipse/Java does not like that because it does not consider "resources.getInteger(R.integer.INTEGER_NAME)" to be a constant. Is there some way to get the compiler and/or Eclipse to see that it is a constant, or do I just need to live with if/else chains?
Edit: I tried doing "final int INTEGER_NAME = resources.getInteger(R.integer.INTEGER_NAME)" and using INTEGER_NAME in the case statement, but that didn't work either.
Upvotes: 3
Views: 4566
Reputation: 2346
i tryed these and it worked
Resources r = getResources();
int i = r.getInteger(R.integer.lol);
switch (i) {
case 1:
Log.d("lol", "hehehe0");
break;
default:
break;
}
Upvotes: 0
Reputation: 64700
Well, resources.getInteger(R.integer.INTEGER_NAME)
is no more a constant than resources.getString(R.string.STRING_NAME)
: its a lookup, so you're not really going to be able to use them in a case statement. You'll have to live with the if/else chain.
Upvotes: 2
Reputation: 234847
Technically, your integer resource values are not constants. How is the compiler supposed to know the value for each case? There's always the possibility of retrieving different values for different configurations. (You could, for instance, have a values-land
resource folder with different values for landscape.) Or you could just change the values in the xml file.
If they are truly constants, define them in code. The only other alternative I can see is to create a dispatch table of Runnable (or Callable) objects, one for each branch of the switch, and retrieve the appropriate one based on the value retrieved from the resources.
Upvotes: 3