4

Is there a better way to do this:

 int drawable; switch(mSignalStrength) { case 0: drawable = R.drawable.signal_0; break; case 1: drawable = R.drawable.signal_1; break; case 2: drawable = R.drawable.signal_2; break; case 3: drawable = R.drawable.signal_3; break; case 4: drawable = R.drawable.signal_4; break; case 5: drawable = R.drawable.signal_5; break; default: drawable = -1; } 

I'm trying to replace the switch statement with some int getDrawableIdByString("signal_" + mSignalStrength) function.

5
  • What is the problem in that Commented Nov 2, 2015 at 9:36
  • 4
    Use reflection: getIdentifier(). You can return the resource id by passing its name. Commented Nov 2, 2015 at 9:40
  • @warlock I've got the same code repeated 6 times, for different values of signal strength. That's ugly. Commented Nov 2, 2015 at 10:14
  • @chrisdew, this is just a switch case , this will run on behalf of the value provided in mSignalStrength, In that case of repeating you should post the complete problem, what you are trying to achieve and how Commented Nov 2, 2015 at 10:17
  • @warlock Thanks, I've amended the question. Commented Nov 2, 2015 at 10:28

3 Answers 3

9

As someone mentioned in the comments, you can use the

getIdentifier(String name, String defType, String defPackage)

For you case, like this

int resId = getResources().getIdentifier("signal_" + mSignalStrength, "drawable", getPackageName()); 
Sign up to request clarification or add additional context in comments.

Comments

2

By using reflection, you can return the resource id by passing its name.
This is what I use when I need something like that:

1 - Add this method to your code:

protected final static int getResourceID (final String resName, final String resType, final Context ctx) { final int ResourceID = ctx.getResources().getIdentifier(resName, resType, ctx.getApplicationInfo().packageName); if (ResourceID == 0) { throw new IllegalArgumentException ( "No resource string found with name " + resName ); } else { return ResourceID; } } 

2 - Use it like this:

int myID = getResourceID("your_resource_name", "drawable", getApplicationContext()); 

Note (1): no path (and no extension, in case of images).
Note (2): use "drawable" for drawables, "string" for strings, ...

Comments

0

The way you're doing it is the most readable and robust way.

It allows you to add / remove items later down the line and doesn't tie you in to a specific naming convention.

It's easier to read because you can just click through to the drawable resource from the code and see for yourself exactly which drawable matches which case -- something that becomes a bit harder when you're generating the id this way.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.