random genaration of image from drawable folder in android
android, image, random
Solution
One way is to create an array with required image's ids. And take random one from that array. That approach is explained in other answers.
Another way is to create file `random_images_array.xml` in `values` folder of your project and fill it like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="apptour">
<item>@drawable/image_1</item>
<item>@drawable/photo_2</item>
<item>@drawable/picture_4</item>
</array>
</resources>
And then you can take random image from that xml array:
final TypedArray imgs = getResources().obtainTypedArray(R.array.random_images_array);
final Random rand = new Random();
final int rndInt = rand.nextInt(imgs.length());
final int resID = imgs.getResourceId(rndInt, 0);
Third method is to take random field from R.drawable class:
final Class drawableClass = R.drawable.class;
final Field[] fields = drawableClass.getFields();
final Random rand = new Random();
int rndInt = rand.nextInt(fields.length);
try {
int resID = fields[rndInt].getInt(drawableClass);
img.setImageResource(resID);
} catch (Exception e) {
e.printStackTrace();
}
Problem
Android version:4.2 I am developing an android App. I need to generate images from drawable folder randomly. In my drawable I have 45 images with different names. My xml code is: ``` <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> ``` I have tried with this code: ``` ImageView img=(ImageView)findViewById(R.id.imageView1); Random rand = new Random(); int rndInt = rand.nextInt(52) + 1; String drawableName = "photo"+ rndInt; int resID = getResources().getIdentifier(drawableName, "drawable", getPackageName()); img.setImageResource(resID); ``` But with this code I need to change my image names to `photo1`, `photo2`, ... and I don't want to do it. Any suggestion on how to implement it? Thank you.