-1

I would like to replace the default ImageView with a random drawable file. I'm trying to use a string that will call a resource_name in java with a variable string that changes based on the user's input.

JAVA code

String random1 = userinput_1;
String random2 = userinput_2;
String replaceImageView = (random1+"_"+random2);
orignalImageView.setImageResource(R.drawable.replaceImageView);
Shawn
  • 1,222
  • 1
  • 18
  • 41
  • Mike M could you please help apply the logic in those question to mine. I'm lost and have been at this problem for over a week and I'm not seeing how those questions help me. – Shawn Oct 10 '17 at 03:16

1 Answers1

1

You need to get the identifier using the name, then use it as you would normally

String random1 = userinput_1;
String random2 = userinput_2;
String replaceImageView = (random1+"_"+random2);
int drawableResourceId = this.getResources().getIdentifier(replaceImageView, "drawable", this.getPackageName());
orignalImageView.setImageResource(drawableResourceId);
Alirio Mendes
  • 809
  • 1
  • 11
  • 16
  • I have tried using drawable ResourceId as an int and a String without any luck. Android studio keeps hightlights the R.drwable.**drawableResourceId) ** as an error. I'm not sure why I'm doing wrong here, Should I be calling the drawable file a different way? – Shawn Oct 10 '17 at 03:09
  • 1
    You don't need "R.drwable.", just "drawableResourceId", you just have to make sure the String replaceImageView matches the resource name exactly. – Alirio Mendes Oct 10 '17 at 07:32
  • That did thanks Alirio – Shawn Oct 12 '17 at 03:49