方法一:
利用getResources().getIdentifier(String name,String defType,String defPackage) 获取
public int getResource(String imageName){
Context ctx=getBaseContext();
int resId = getResources().getIdentifier(imageName, "mipmap", ctx.getPackageName());
//如果没有在"mipmap"下找到imageName,将会返回0
return resId;
}
方法二:
使用反射机制获取
public int getMipmapResource(String imageName) {
Class mipmap = R.mipmap.class;
try {
Field field = mipmap.getField(imageName);
int resId = field.getInt(imageName);
return resId;
} catch (NoSuchFieldException e) {//如果没有在"mipmap"下找到imageName,将会返回0
return 0;
} catch (IllegalAccessException e) {
return 0;
}
}