Android, getting resource ID from string?

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

    For getting Drawable id from String resource name I am using this code:

    private int getResId(String resName) {
        int defId = -1;
        try {
            Field f = R.drawable.class.getDeclaredField(resName);
            Field def = R.drawable.class.getDeclaredField("transparent_flag");
            defId = def.getInt(null);
            return f.getInt(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            return defId;
        }
    }
    

提交回复
热议问题