J. Redhill J. Redhill - 6 months ago 12
Java Question

Asking for name of image in if statement

My Question is, how to ask in if statement for the name of an image in a ImageView. I have tried it with image.equals("imageName") but it doesn't work.
I will display Random images my Code looks like:

Random rand = new Random();
String str = "img_" + rand.nextInt(3);


In the if statement I have tried this:

if (str.equals("img_" + 1)){...}


And my ImageView, wich shows a Random image (this works fine) looks like this:

image = (ImageView) findViewById(R.id.imageView);
image.setImageDrawable(getResources().getDrawable(getResourceID(str, "drawable", getApplicationContext())));


I think, i have to handle with "image" and not "str" but i don't know how???

Answer

I'm not sure what you expected to happen by comparing an ImageView to a String. Those are not the same type, so equalling them won't work.

If you'd like to associate the ImageView with some object, then you can use tags.

Random rand = new Random();
String str = "img_" + rand.nextInt(3);
image = (ImageView) findViewById(R.id.imageView);
image.setTag(str);
int resId = getResources().getDrawable(getResourceID(str, "drawable", getApplicationContext()));
image.setImageDrawable(resId);

And check it later

String tag = (String) image.getTag();
if (tag.equals("img_1")){...}