Android中替代getResources().getIdentifier()的方案咨询
替代
getIdentifier()的几种可行方案 方案1:静态HashMap映射表
提前把所有需要用到的图片名称和对应的资源ID做静态映射,直接通过名称查表获取ID,完全避免反射,编译期就能校验资源是否存在。
// 定义全局静态映射表(可放在Actors类或单独工具类中) private static final Map<String, Integer> DRAWABLE_MAP = new HashMap<>(); // 在Application初始化或类加载时初始化映射表 static { DRAWABLE_MAP.put("actor_1", R.drawable.actor_1); DRAWABLE_MAP.put("actor_2", R.drawable.actor_2); // 把所有需要从数据库读取的图片都添加进来 } // 遍历数据库时使用 Cursor res = myDb.getAllData(); while (res.moveToNext()) { Actors actor = new Actors(); actor.setName(res.getString(1)); String th = res.getString(11); // 直接从映射表取ID,不存在则设默认图 Integer thumb = DRAWABLE_MAP.getOrDefault(th, R.drawable.default_thumb); actor.setThumb(thumb); // 注意你原代码存在笔误,应使用thumb变量而非R.drawable.th }
方案2:枚举类绑定资源
用枚举类管理图片名称和资源ID,类型安全更强,还能统一管理所有相关资源,避免拼写错误。
// 定义枚举类 public enum ActorThumb { ACTOR_1("actor_1", R.drawable.actor_1), ACTOR_2("actor_2", R.drawable.actor_2), // 其他图片... DEFAULT("default", R.drawable.default_thumb); private final String name; private final int resId; ActorThumb(String name, int resId) { this.name = name; this.resId = resId; } // 根据名称获取枚举实例 public static ActorThumb getByName(String name) { for (ActorThumb thumb : values()) { if (thumb.name.equals(name)) { return thumb; } } return DEFAULT; } public int getResId() { return resId; } } // 遍历数据库时使用 Cursor res = myDb.getAllData(); while (res.moveToNext()) { Actors actor = new Actors(); actor.setName(res.getString(1)); String th = res.getString(11); int thumbResId = ActorThumb.getByName(th).getResId(); actor.setThumb(thumbResId); }
方案3:APT自动生成映射类(适合大量图片场景)
如果图片数量极多,可以用注解处理器(APT)自动生成映射类:
- 自定义
@DrawableName注解标记需要映射的Drawable资源 - 编写APT处理器,扫描所有带该注解的资源,生成包含
Map<String, Integer>的类 - 运行时直接调用生成类的映射表
这种方式适合大型项目,减少手动维护的工作量。
关于数据库存R.drawable.imagename格式的处理
如果数据库里存的是完整的R.drawable.imagename字符串,可先截取名称部分再用上述方案:
String fullResStr = res.getString(11); // 截取最后一个点后的名称部分 String th = fullResStr.substring(fullResStr.lastIndexOf(".") + 1); // 再用映射表或枚举获取ID
内容的提问来源于stack exchange,提问作者Darksymphony
相关产品推荐
相关产品推荐

