13
如果我知道资源的名称,我如何返回资源的ID?返回资源ID,如果我知道资源的名称
事情是这样的:
String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
如果我知道资源的名称,我如何返回资源的ID?返回资源ID,如果我知道资源的名称
事情是这样的:
String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
在MonoDroid的,该代码转换为类似:
var resourceId = Resources.GetIdentifier(mDrawableName.ToLower(), "drawable", PackageName);
不过,我个人不使用则getIdentifier因为它不是在Android的推荐 - 所以我使用反射代替:
var resourceId = (int)typeof(Resource.Drawable).GetField(mDrawable).GetValue(null);
虽然该代码应该肯定有一些尝试/为任意字符串添加catch错误检查!
非常感谢你! –