rokevin
移动
前端
语言
  • 基础

    • Linux
    • 实施
    • 版本构建
  • 应用

    • WEB服务器
    • 数据库
  • 资讯

    • 工具
    • 部署
开放平台
产品设计
  • 人工智能
  • 云计算
计算机
其它
GitHub
移动
前端
语言
  • 基础

    • Linux
    • 实施
    • 版本构建
  • 应用

    • WEB服务器
    • 数据库
  • 资讯

    • 工具
    • 部署
开放平台
产品设计
  • 人工智能
  • 云计算
计算机
其它
GitHub
  • 资源

资源

根据字符串动态获取资源ID

常用方法

public int getResId(String name,Context context){
    Resources r = context.getResources();
    int id = r.getIdentifier(name,"drawable","com.demo");
    return id;
}

使用反射(推荐,性能高)

public class ResourceMan {
    public static int getResId(String variableName, Class<?> c) {
        try {
            Field idField = c.getDeclaredField(variableName);
            return idField.getInt(idField);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
}

使用方法

int id = ResourceMan.getResId("icon",R.drawable.class);
最近更新:: 2025/10/22 15:36
Contributors: luokaiwen