Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Android getIdentifier()

Tags:

java

android

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 the use of getResources () in Android?

The documentation for getResources() says that it will [r]eturn a Resources instance for your application's package. In code examples I've seen this used to access the resources in res , but it seems like you can just access them directly. For example to retrieve my_string from res/values/strings.

How can I make my name drawable?

public class DrawableManager { private static Context context = null; public static void init(Context c) { context = c; } public static Drawable getDrawable(String name) { return R. drawable.? } }

What is resource in Android Studio?

Resources are the additional files and static content that your code uses, such as bitmaps, layout definitions, user interface strings, animation instructions, and more.


Since you are inside of an activity it is enough to write

int resId = YourActivity.this.getResources().getIdentifier(
    "ball_red",
    "drawable",
    YourActivity.this.getPackageName()
);

or if you're not calling it from an inner class

int resourceID = getResources().getIdentifier(
    "ball_red",
    "drawable",
    getPackageName()
);

Note

getIdentifier() Returns 0 if no such resource was found. (0 is not a valid resource ID.)

Check

Check also in your R.java whether there is a drawable with the name ball_red

e.g.:

public static final class drawable {
        public static final int ball_red = 0x7f020000;
 }

EDIT If you're not in any activity then you must pass a context instead of resources as parameter then do this

int resId = context.getResources().getIdentifier(
    "ball_red",
    "drawable",
    context.getPackageName()
);

For Xamarin users I had the issue where I had added an icon with lower and uppercase letters (e.g. iconVaccine.png ) and was referring to the uppercase name iconVaccine.

Xamarin will allow you to do this (even though you shouldn't), but when the app gets compiled the name are flattened to lower case, so you must refer to the lower case variant as follows:

Image Name: iconVaccine.png

Xamarin reference: iconVaccine (as created in Resource.designer.cs, but will fail)

Correct Reference: iconvaccine

Hope that helps!


Though the answer from Festus Tamakloe is correct I found a quirk in this function.

If you are declaring a string-array in a xml file it must be accessed by calling the base resource type array, using string-array results in anid 0 return.