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.
How about
or
and
You have to see this question or answer also:-
Randomize string from resources android
but you have to replace
to
Be specific about your question - what do you actually want to do?
if you want to show images in random order than this would be best
If you want the absolute file path of image to rename it, see this article for details.
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
invalues
folder of your project and fill it like this:And then you can take random image from that xml array:
Third method is to take random field from R.drawable class: