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

前端 未结 10 1268
挽巷
挽巷 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:19
    int resourceID = 
        this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
    
    0 讨论(0)
  • 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.<b>image</b>
     * @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;
    
    }
    
    0 讨论(0)
  • 2020-11-22 00:31

    In Kotlin following works fine for me:

    val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())
    

    If resource is place in mipmap folder, you can use parameter "mipmap" instead of "drawable".

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

    I have found this class very helpful to handle with resources. It has some defined methods to deal with dimens, colors, drawables and strings, like this one:

    public static String getString(Context context, String stringId) {
        int sid = getStringId(context, stringId);
        if (sid > 0) {
            return context.getResources().getString(sid);
        } else {
            return "";
        }
    }
    
    0 讨论(0)
提交回复
热议问题