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

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

提交回复
热议问题