Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android/java getIdentifier with

Tags:

java

android

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?

like image 756
Ashley Avatar asked Jan 22 '11 23:01

Ashley


People also ask

What is getIdentifier?

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)

What is getResources() in Android?

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() .

What is GetDrawable return?

GetDrawable(Int32) Return a drawable object associated with a particular resource ID.

What is resource value in Android Studio?

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.


1 Answers

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

like image 51
Helton Isac Avatar answered Sep 28 '22 08:09

Helton Isac