-1

I have a lot of images (hundreds) and I need to put some of them as a resource of ImageView, but if I would create If Then set Image to Image name, I die from these tons of code. I want to set Image resource which name is inside a variable, but I can't find out how. If I have img.setImageResource(R.drawable.my_image); How can I assign variable name at my_image instead of true image name? Please help. Thanks.

Phantômaxx
  • 36,442
  • 21
  • 78
  • 108
  • Possible duplicate of [Android getResources().getDrawable() deprecated API 22](https://stackoverflow.com/questions/29041027/android-getresources-getdrawable-deprecated-api-22) – shizhen Apr 02 '19 at 15:10

3 Answers3

0

Try this:

 String resourceName = "clouds";
 int resourceIdentifier = getResources().getIdentifier(resourceName, "drawable", Constants.CURRENT_CONTEXT.getPackageName());

Then

imgView.setImageResource(resourceIdentifier);
S-Sh
  • 2,986
  • 3
  • 9
  • 15
0

I don't know if I clearly understood your request but why don't you try to do that instead :

    int my_image = R.id.my_image;
    img.setImageResource(ContextCompat.getDrawable(this, my_image));

https://stackoverflow.com/a/29146895/8526518 for more informations about ContextCompat

Adama Traore
  • 111
  • 7
0

if you can prefer assets folder rather than resource, then you can try this code

create sub-folder in assets directory. use getAssets().list() for getting all file names from assets:

String[] images =getAssets().list("images");
ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));

Now to set image in imageview you first need to get bitmap using image name from assets :

InputStream inputstream=mContext.getAssets().open("images/"
                                      +listImages.get(position));
Drawable drawable = Drawable.createFromStream(inputstream, null);
imageView.setImageDrawable(drawable);
Amar Sharma
  • 153
  • 1
  • 1
  • 8