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

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

提交回复
热议问题