James
James

Reputation: 14101

How to show random images on Android?

I have a number of images in my directory. I want to show random images in ANDROID. Please anyone provide me with an example.

Upvotes: 3

Views: 15231

Answers (3)

anon
anon

Reputation:

You have to combine some things. First you need an ImageView in order to display an image on the Android phone.

Then I would take a look into a random number generator (e.g. http://docs.oracle.com/javase/6/docs/api/java/util/Random.html) so that you can get a random number.

By combining these to things, you can randomly select a picture from a list of available pictures and display it using the ImageView.

Upvotes: 1

Itsik
Itsik

Reputation: 3930

Assume that your images are named img1.png, img2.png, and so on, and they are located in res/drawable folder.

Then you can use the following code to randomly set an image in an ImageView

ImageView imgView = new ImageView(this);
Random rand = new Random();
int rndInt = rand.nextInt(n) + 1; // n = the number of images, that start at idx 1
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());  
imgView.setImageResource(id); 

Upvotes: 6

Raj
Raj

Reputation: 1770

I don't have an example but I can provide you an idea.

  1. Build a list of images in an array
  2. Generate a random number between 0 to 1 less than the number of images in folder
  3. Use the random number in step 2 as an index to the array and pick up the image for display.

Upvotes: 1

Related Questions