Question

I have few images in my app ( they are all copied into res/drawable and have appropriate R.drawable reference) that I want to assign them to my ImageViews using contents of an string type variable. To illustrated, I have an image file named "c4.png" in my drawable folder and an string variable (card) that contains "c4". I want to see if there is any way I can use a code like this (ImageView1.setImageResource(R.drawable.card)) to assign image c4 to my ImageView1 instead of using ImageView1.setImageResource(R.drawable.c4). Basically, I am wondering if it is possible to replace a variable with the specific image name in the R.drawable.resourceName. I know that R.drawable.resourceName is an integer and I am not trying to change its type. I want to replace the resourceName with a variable. I appreciate any help

Was it helpful?

Solution

Use this to draw a random number in particular range-

int min = 0;
int max = 9;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;

Then using this number pick image from image array-

public Integer[] nImages = {
                R.drawable.c1, R.drawable.c2,
                R.drawable.c3, R.drawable.c4,
                R.drawable.c5, R.drawable.c6,
                R.drawable.c7, R.drawable.c8,
                R.drawable.c9, R.drawable.c10
    };

ImageView1.setBackgroundResource(nImages [i1]);

Hope this works.

OTHER TIPS

Try this

Resources res = getResources();

int id = res.getIdentifier(card, "drawable", getPackageName());
img.setImageResource(id);

this may solve your problem.

Or you can put the images in the asset folder. Assets are referenced by their filename, as in

getAssets().open(<filename>);

This returns an InputStream. Afterwhich it is trivial to convert them to a Bitmap resource

BitmapFactory.decodeStream(inputStream);

And then use that bitmap for your ImageView. That should be straightforward with

imageView.setImageBitmap(bitmap);

I want to replace the resourceName with a variable.

Instead of declaring the variable card as a string declare it as an Integer. So that you can use it like the following.

int card=R.drawable.c4;
ImageView1.setImageResource(card);

You probably can not do something like R.drawable.card because the R file is generated according to the resources in the drawable folder. hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top