Android, getting resource ID from string?

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

    I did like this, it is working for me:

        imageView.setImageResource(context.getResources().
             getIdentifier("drawable/apple", null, context.getPackageName()));
    
    0 讨论(0)
  • 2020-11-22 00:05

    Since you said you only wanted to pass one parameter and it did not seem to matter which, you could pass the resource identifier in and then find out the string name for it, thus:

    String name = getResources().getResourceEntryName(id);
    

    This might be the most efficient way of obtaining both values. You don't have to mess around finding just the "icon" part from a longer string.

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

    This is based on @Macarse answer.

    Use this to get the resources Id in a more faster and code friendly way.

    public static int getId(String resourceName, Class<?> c) {
        try {
            Field idField = c.getDeclaredField(resourceName);
            return idField.getInt(idField);
        } catch (Exception e) {
            throw new RuntimeException("No resource ID found for: "
                    + resourceName + " / " + c, e);
        }
    }
    

    Example:

    getId("icon", R.drawable.class);
    
    0 讨论(0)
  • 2020-11-22 00:07
    Simple method to get resource ID:
    
    public int getDrawableName(Context ctx,String str){
        return ctx.getResources().getIdentifier(str,"drawable",ctx.getPackageName());
    }
    
    0 讨论(0)
  • 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.

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

    In MonoDroid / Xamarin.Android you can do:

     var resourceId = Resources.GetIdentifier("icon", "drawable", PackageName);
    

    But since GetIdentifier it's not recommended in Android - you can use Reflection like this:

     var resourceId = (int)typeof(Resource.Drawable).GetField("icon").GetValue(null);
    

    where I suggest to put a try/catch or verify the strings you are passing.

    0 讨论(0)
提交回复
热议问题