tags:

views:

78

answers:

3

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

+1  A: 

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.
Raj
-1 It's redundant to build a list of images in an array, all the images id's are automatically generated in the class R. Its also not that maintainable, you will need to add the image to the array upon every image addition.
Itsik
+1  A: 

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://download-llnw.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.

Roflcoptr
+3  A: 

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); 
Itsik
hi, this is working great...can u let me knwhow can i get unique image everytime.i mean,if i am giving n= 7, and calling this function 7 times only, each time it should givE A unique images?how can i do this?thanks
shishir.bobby
Random is a random generator, and should give a random number between 0..n-1 every time you run nextInt(). If you have files named img1, img2, ... img7, then it should give a random image. If you want to call this ONLY 7 times, then you should implement a method that will give you a random permutation of 1..7, and then display the images according the their order in the permutation.
Itsik