Reputation: 44739
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.
Upvotes: 3
Views: 6902
Reputation: 38098
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, ...
Upvotes: 2
Reputation: 2321
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.
Upvotes: 0
Reputation: 20513
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());
Upvotes: 8