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

前端 未结 10 1227
挽巷
挽巷 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:24

    I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.

    Here's the code:

    /**
     * @author Lonkly
     * @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 с) {
    
        Field field = null;
        int resId = 0;
        try {
            field = с.getField(variableName);
            try {
                resId = field.getInt(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resId;
    
    }
    

提交回复
热议问题