Android, getting resource ID from string?

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

    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);
    

提交回复
热议问题