You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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)自动生成映射类:

  1. 自定义@DrawableName注解标记需要映射的Drawable资源
  2. 编写APT处理器,扫描所有带该注解的资源,生成包含Map<String, Integer>的类
  3. 运行时直接调用生成类的映射表

这种方式适合大型项目,减少手动维护的工作量。

关于数据库存R.drawable.imagename格式的处理

如果数据库里存的是完整的R.drawable.imagename字符串,可先截取名称部分再用上述方案:

String fullResStr = res.getString(11);
// 截取最后一个点后的名称部分
String th = fullResStr.substring(fullResStr.lastIndexOf(".") + 1);
// 再用映射表或枚举获取ID

内容的提问来源于stack exchange,提问作者Darksymphony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 09:11:31