Android, getting resource ID from string?

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

    How to get an application resource id from the resource name is quite a common and well answered question.

    How to get a native Android resource id from the resource name is less well answered. Here's my solution to get an Android drawable resource by resource name:

    public static Drawable getAndroidDrawable(String pDrawableName){
        int resourceId=Resources.getSystem().getIdentifier(pDrawableName, "drawable", "android");
        if(resourceId==0){
            return null;
        } else {
            return Resources.getSystem().getDrawable(resourceId);
        }
    }
    

    The method can be modified to access other types of resources.

提交回复
热议问题