Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return id of resource, if i know name of resource

How i can return id of resource, if i know name of resource?

Something like this:

String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
like image 915
Andrew Andreev Avatar asked Oct 23 '12 20:10

Andrew Andreev


People also ask

How do I find the image ID of a resource?

I'll use getResources(). getIdentifier(name, "id", getPackageName()); to get the ID of an ImageButton (as you would with R.id.name). @Srujan Barai, getResource() and getPackageName() are methods from Activity.

What is a resource ID?

Description The Resource ID field contains the identifier number that Project assigns to each resource. The Resource ID indicates the position of the resource in relation to other resources. How Calculated As you add resources, Project automatically assigns the next number in the sequence of resources as listed.

How do I find my resource ID Android?

int resourceId = this. getResources(). getIdentifier("nameOfResource", "id", this.


1 Answers

In MonoDroid, that code translates to something like:

 var resourceId = Resources.GetIdentifier(mDrawableName.ToLower(), "drawable", PackageName);

However, I personally don't use GetIdentifier as it's not recommended in Android - so I use Reflection instead:

 var resourceId = (int)typeof(Resource.Drawable).GetField(mDrawable).GetValue(null);

although that code should definitely have some try/catch error checking added for arbitrary strings!

like image 97
Stuart Avatar answered Sep 23 '22 16:09

Stuart