-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
  • 37,901
  • 21
  • 84
  • 115
  • 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

4 Answers4

1

Try this:

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

Then

imgView.setImageResource(resourceIdentifier);
S-Sh
  • 3,564
  • 3
  • 15
  • 19
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
  • 192
  • 1
  • 10
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
  • 173
  • 1
  • 2
  • 10
0

just a convenient refactoring of the S-Sh answer if you use kotlin and like using its extensions functions:

fun ImageView.loadDrawableFromName(name:String, ctx: Context, visible:Int=View.VISIBLE){
    val resId = ctx.resources.getIdentifier(name, "drawable", ctx.packageName)
    this.setImageResource(resId)
    this.visibility = visible
}

you can call it in both ways:

imgname="IMGNAME"
myimageview.loadDrawableFromName(imgname, ctx)

and

imgname="IMGNAME"
myimageview.loadDrawableFromName("@drawable/$imgname", ctx)
albaspazio
  • 121
  • 1
  • 6