Android, getting resource ID from string?

后端 未结 14 1674
忘掉有多难
忘掉有多难 2020-11-21 23:56

I need to pass a resource ID to a method in one of my classes. It needs to use both the id that the reference points to and also it needs the string. How should I best achie

14条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 00:06

    This is based on @Macarse answer.

    Use this to get the resources Id in a more faster and code friendly way.

    public static int getId(String resourceName, Class c) {
        try {
            Field idField = c.getDeclaredField(resourceName);
            return idField.getInt(idField);
        } catch (Exception e) {
            throw new RuntimeException("No resource ID found for: "
                    + resourceName + " / " + c, e);
        }
    }
    

    Example:

    getId("icon", R.drawable.class);
    

提交回复
热议问题