今天和小伙伴讨论的时候遇到一个问题,就是根据后台返回的值,app动态去设置图片,然后后台返回的值中有一个string, 例如v0,和我们图片名字的一部分相似,如img_v0,
如何去动态设置呢,这里牵扯到一些东西,我们可以根据名字去找到对应资源的ID,从而动态设置资源,没有什么不可能
方案一:
利用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 getResource(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;
}
}
好了 over 下面附上我的工具类
public class ResIdUtil {
/**
* 获取id
*
* @param resName 资源名称
* @return 资源id
*/
public static int id(Context context, String resName) {
return context.getResources().getIdentifier(resName, "id", context.getPackageName());
}
/**
* 获取anim类型资源id
*
* @param resName 资源名称
* @return 资源id
*/
public static int anim(Context context, String resName) {
return context.getResources().getIdentifier(resName, "anim", context.getPackageName());
}
/**
* 获取layout类型资源id
*
* @param resName 资源名称
* @return 资源id
*/
public static int layout(Context context, String resName) {
return context.getResources().getIdentifier(resName, "layout", context.getPackageName());
}
/**
* 获取drawable类型资源id
*
* @param resName 资源名称
* @return 资源id
*/
public static int drawable(Context context, String resName) {
return context.getResources().getIdentifier(resName, "drawable", context.getPackageName());
}
/**
* 获取string类型资源id
*
* @param resName 资源名称
* @return 资源id
*/
public static int string(Context context, String resName) {
return context.getResources().getIdentifier(resName, "string", context.getPackageName());
}
/**
* 获取raw类型资源id
*
* @param resName 资源名称
* @return 资源id
*/
public static int raw(Context context, String resName) {
return context.getResources().getIdentifier(resName, "raw", context.getPackageName());
}
/**
* 获取style类型资源id
*
* @param resName 资源名称
* @return 资源id
*/
public static int style(Context context, String resName) {
return context.getResources().getIdentifier(resName, "style", context.getPackageName());
}
}