How to replace R.drawable.“someString”

2019-03-11 02:38发布

问题:

I have some Images in my project. The name of the image is stored in a String and I would like to setImageResource(R.drawable."....."); with the string of the image name but the problem is that this is not working.

How can I do this?

回答1:

this is not a right syntax, and you must getting compiler time error, before altering image resource you must know that, all resources provided an id, these ids are stored into R.java file. Ids are stored into integer format, and in your application you can fetch all these resources by these id, not by name, so you need to fetch id of resource at first, by:

String mDrawableName = "myimg";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

and then use this resID.



回答2:

Use

getResources().getIdentifier("NAME_OF_IMAGE", "drawable", context.getPackageName())


回答3:

See this thread. It should help you. Basically you need to get the identifier and then load using setImageResource.



回答4:

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

name - name of the image
defType - it will be drawable for your case
defPackage - default package of your app (I think you can use getPackage() on the activity for this)



回答5:

try this

   String uri = "NAME";

    // int imageResource = R.drawable.icon;
    int imageResource = getResources().getIdentifier(uri, null, getPackageName());

    ImageView imageView = (ImageView) findViewById(R.id.myImageView);
    Drawable image = getResources().getDrawable(imageResource);
    imageView.setImageDrawable(image);


回答6:

I got it working by moving the image from 'drawable' to 'raw' folder and access the string value as below. If you do not have 'raw' folder under 'res' directory, right click on res->new->Android resource directory and under dropdown of resourcetype, select 'raw'.

    String avatar = ("android.resource://" + "yourPackageName/" + String.valueOf(R.raw.robot_blue));