Android, getting resource ID from string?

后端 未结 14 1339
忘掉有多难
忘掉有多难 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:26

    @EboMike: I didn't know that Resources.getIdentifier() existed.

    In my projects I used the following code to do that:

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

    It would be used like this for getting the value of R.drawable.icon resource integer value

    int resID = getResId("icon", R.drawable.class); // or other resource class
    

    I just found a blog post saying that Resources.getIdentifier() is slower than using reflection like I did. Check it out.

    0 讨论(0)
  • 2020-11-22 00:29

    If you need to pair a string and an int, then how about a Map?

    static Map<String, Integer> icons = new HashMap<String, Integer>();
    
    static {
        icons.add("icon1", R.drawable.icon);
        icons.add("icon2", R.drawable.othericon);
        icons.add("someicon", R.drawable.whatever);
    }
    
    0 讨论(0)
提交回复
热议问题