random genaration of image from drawable folder in android -


Android version: 4.2
I'm developing Android app. I need to create a picture randomly from the drawable folder. In my picture, I have 45 images, which are different names. My XML code:

  Android: Image = "@ + ID / Image View 1" 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 Drawable name = "photo" + rndInt; Int resID = getResources (). GetIdentifier (drawableName, "drawable", getPackageName ()); Img.setImageResource (Resid);   

But with this code I have to change my image names to photo1 , photo2 and I do not want to do this for.

Any suggestions about applying it? Thank you.

One way to create an array with the required image ID and take random one from that array That approach is explained in the other answer.

Another way is to enter the random_images_array.xml in the value folder of your project and fill it like this:

 < Code> & lt ;? Xml version = "1.0" encoding = "UTF-8"? & Gt; & Lt; Resources & gt; & Lt; Array name = "epiphur" & gt; & Lt; Items & gt; @ Drawable / IMAGE_1 & lt; / Item & gt; & Lt; Items & gt; @ Drawable / photo_2 & lt; / Item & gt; & Lt; Items & gt; @ Drawable / picture_4 & lt; / Item & gt; & Lt; / Array & gt; & Lt; / Resources & gt;   

And then you can take a random image from that XML array:

  last typedArray = getResources (). GetTypedArray (R.array.random_images_array); Final Random = New Random (); Final int rndInt = rand.nextInt (imgs.length ()); Final integer resID = imgs.getResourceId (rndInt, 0);   

The third method is to take random areas from the R.Drawable class:

  final range drawableClass = R.drawable.class; Last field [] field = drawable class .getFields (); Final Random = New Random (); Int rndInt = rand.nextInt (fields.length); {Int resID = field [rndInt] Try .getInt (drawableClass); Img.setImageResource (Resid); } Hold (exception e) {e.printStackTrace (); }    

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -