I'm having trouble getting getIdentifier
to work with a class variable. It's strange, because this works:
public Drawable getStationIcon(Context context) {
int resId = context.getResources().getIdentifier("m1m2_16", "drawable", "com.mypackage.namehere");
Drawable drawable = context.getResources().getDrawable(resId);
return drawable;
}
But this doesn't:
public Drawable getStationIcon(Context context) {
int resId = context.getResources().getIdentifier(this.stationIcon, "drawable", "com.mypackage.namehere");
Drawable drawable = context.getResources().getDrawable(resId);
return drawable;
}
And nor does this:
public Drawable getStationIcon(Context context) {
String stationI = this.stationIcon;
int resId = context.getResources().getIdentifier(stationI, "drawable", "com.mypackage.namehere");
Drawable drawable = context.getResources().getDrawable(resId);
return drawable;
}
And this.stationIcon
definitely equals m1m2_16
. I've tried other alternatives, ie using ""+this.stationIcon
, but nothing works when the first parameter is a variable. Is there something I'm missing?
getIdentifier does is to allow resolving resource integer constants using the name of the resource. For example if we want to set the background in a View, we can do as usual: // Set the resource by using the its identifier (resource integer constant) view.setBackground(R.drawable.my_red_box)
The Android resource system keeps track of all non-code assets associated with an application. You can use this class to access your application's resources. You can generally acquire the Resources instance associated with your application with getResources() .
GetDrawable(Int32) Return a drawable object associated with a particular resource ID.
Resources are used for anything from defining colors, images, layouts, menus, and string values. The value of this is that nothing is hardcoded. Everything is defined in these resource files and then can be referenced within your application's code.
Strangely it will probably work:
getIdentifier("com.mypackage.namehere:drawable/" + this.stationIcon, null, null);
Credit: https://stackoverflow.com/users/790997/idroid
Resources.getIdentifier() has unexpected behavior when name is numeric
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