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

前端 未结 10 1287
挽巷
挽巷 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.

提交回复
热议问题