16

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());
4

1 回答 1

34

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!

于 2012-10-23T21:19:38.793 回答