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

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

    It will be something like:

    R.drawable.resourcename

    Make sure you don't have the Android.R namespace imported as it can confuse Eclipse (if that's what you're using).

    If that doesn't work, you can always use a context's getResources method ...

    Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);
    

    Where this.context is intialised as an Activity, Service or any other Context subclass.

    Update:

    If it's the name you want, the Resources class (returned by getResources()) has a getResourceName(int) method, and a getResourceTypeName(int)?

    Update 2:

    The Resources class has this method:

    public int getIdentifier (String name, String defType, String defPackage) 
    

    Which returns the integer of the specified resource name, type & package.

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

    If I understood right, this is what you want

    int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());
    

    Where "this" is an Activity, written just to clarify.

    In case you want a String in strings.xml or an identifier of a UI element, substitute "drawable"

    int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());
    

    I warn you, this way of obtaining identifiers is really slow, use only where needed.

    Link to official documentation: Resources.getIdentifier(String name, String defType, String defPackage)

    0 讨论(0)
  • 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.<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<?> с)
                         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());
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:12
    // image from res/drawable
        int resID = getResources().getIdentifier("my_image", 
                "drawable", getPackageName());
    // view
        int resID = getResources().getIdentifier("my_resource", 
                "id", getPackageName());
    
    // string
        int resID = getResources().getIdentifier("my_string", 
                "string", getPackageName());
    
    0 讨论(0)
  • 2020-11-22 00:13

    Kotlin Version via Extension Function

    To find a resource id by its name In Kotlin, add below snippet in a kotlin file:

    ExtensionFunctions.kt

    import android.content.Context
    import android.content.res.Resources
    
    fun Context.resIdByName(resIdName: String?, resType: String): Int {
        resIdName?.let {
            return resources.getIdentifier(it, resType, packageName)
        }
        throw Resources.NotFoundException()
    }
    


    Usage

    Now all resource ids are accessible wherever you have a context reference using resIdByName method:

    val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
    val stringResId = context.resIdByName("title_home", "string")
    .
    .
    .    
    
    0 讨论(0)
  • 2020-11-22 00:16

    A simple way to getting resource ID from string. Here resourceName is the name of resource ImageView in drawable folder which is included in XML file as well.

    int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
    ImageView im = (ImageView) findViewById(resID);
    Context context = im.getContext();
    int id = context.getResources().getIdentifier(resourceName, "drawable",
    context.getPackageName());
    im.setImageResource(id);
    
    0 讨论(0)
提交回复
热议问题