有时候想在代码运行的时候根据资源名称去获取id从而使用调用资源文件。
Resource中的getIdentifier()可以解决这个问题
public int getIdentifier(String name, String defType, String defPackage) {return mResourcesImpl.getIdentifier(name, defType, defPackage);}
使用方法:
int resId = context.getResources().getIdentifier(paramString,"mipmap", context.getPackageName());
除了上面案例中的mipmap可以这样使用之后,以下类型的都可以
- layout
- string
- array
- drawable
- style
- id
- color
- attr
- styleable
- mipmap
封装工具类
public class ResourceUtil {public static int getLayoutId(Context context, String resName) { return context.getResources().getIdentifier(resName, "layout", context.getPackageName()); } public static int getStringId(Context context, String resName) { return context.getResources().getIdentifier(resName, "string", context.getPackageName()); }public static int getArrayId(Context context, String resName) {return context.getResources().getIdentifier(resName, "array",context.getPackageName());}public static int getDrawableId(Context context, String resName) { return context.getResources().getIdentifier(resName, "drawable", context.getPackageName()); } public static int getStyleId(Context context, String resName) { return context.getResources().getIdentifier(resName, "style", context.getPackageName()); } public static int getId(Context context, String resName) { return context.getResources().getIdentifier(resName, "id", context.getPackageName()); } public static int getColorId(Context context, String resName) { return context.getResources().getIdentifier(resName, "color", context.getPackageName()); }public static int getAttrId(Context context, String resName) {return context.getResources().getIdentifier(resName,"attr", context.getPackageName());}public static int getStyleableId(Context context, String resName) {return context.getResources().getIdentifier(resName,"styleable", context.getPackageName());}public static int getMipmapId(Context context, String resName) {return context.getResources().getIdentifier(resName,"mipmap", context.getPackageName());}
}