有时候想在代码运行的时候根据资源名称去获取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 conte