简体   繁体   中英

Can Android Integer resources be used in switch statements?

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM