2

I have a string with the name of the file that I want (R.drawable.square) to put in the imageview.

String shape = "square"

I am trying to use the method below to show the image

imageView.setImageResource()

Hardcoding the filename in works but I want to be able to pass different filenames in.

image.setImageResource(R.drawable.square)

tl;dr can't get from String:"square" to int:R.drawable.square

Rory Harrison
  • 117
  • 10
  • let's try this https://stackoverflow.com/questions/6783327/setimageresource-from-a-string – Nam Hoang Mar 10 '18 at 02:34
  • Possible duplicate of [Android, reference things in R.drawable. using variables?](https://stackoverflow.com/questions/7941304/android-reference-things-in-r-drawable-using-variables) – ADM Mar 10 '18 at 02:59

3 Answers3

3

Please see Android, reference things in R.drawable. using variables?

//to retrieve image in res/drawable and set image in ImageView
String imageName = "picture"
int resID = getResources().getIdentifier(imageName, "drawable", "package.name");
ImageView image;
image.setImageResource(resID );
Mark Han
  • 2,785
  • 2
  • 16
  • 31
0

I achieved the effect by putting the images in the assets directory

SadeepDarshana
  • 1,057
  • 18
  • 34
0

I think it's better to use you Strings as key and your resource ids as value in a Map Object.

    Map<String, Integer> resources = new HashMap<>();

    resources.put("square", R.drawable.square);
    // resources.put("...", R.drawable....);

    imageView.setImageResource(resources.get("square"));
Mahdi-Malv
  • 16,677
  • 10
  • 70
  • 117