How to get a resource id with a known resource name?

前端 未结 10 1263
挽巷
挽巷 2020-11-21 23:31

I want to access a resource like a String or a Drawable by its name and not its int id.

Which method would I use for this?

10条回答
  •  隐瞒了意图╮
    2020-11-22 00:07

    in addition to @lonkly solution

    1. see reflections and field accessibility
    2. unnecessary variables

    method:

    /**
     * lookup a resource id by field name in static R.class 
     * 
     * @author - ceph3us
     * @param variableName - name of drawable, e.g R.drawable.image
     * @param с            - class of resource, e.g R.drawable.class or R.raw.class
     * @return integer id of resource
     */
    public static int getResId(String variableName, Class с)
                         throws android.content.res.Resources.NotFoundException {
        try {
            // lookup field in class 
            java.lang.reflect.Field field = с.getField(variableName);
            // always set access when using reflections  
            // preventing IllegalAccessException   
            field.setAccessible(true);
            // we can use here also Field.get() and do a cast 
            // receiver reference is null as it's static field 
            return field.getInt(null);
        } catch (Exception e) {
            // rethrow as not found ex
            throw new Resources.NotFoundException(e.getMessage());
        }
    }
    

提交回复
热议问题