Return id of resource, if i know name of resource

2019-01-24 04:33发布

问题:

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

回答1:

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!