美文网首页
Android根据字符串获取资源id

Android根据字符串获取资源id

作者: 编程灯塔2 | 来源:发表于2017-07-14 17:02 被阅读0次

实际我们需要获取的是R.drawable 中一个变量,可以用反射:

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("fuck", R.drawable.class);

相关文章

网友评论

      本文标题:Android根据字符串获取资源id

      本文链接:https://www.haomeiwen.com/subject/felohxtx.html