How to show random images on Android?

I have several images in my directory. I want to show random images in ANDROID. Please give me an example.

+3
source share
3 answers

Suppose your images are called img1.png, img2.png, etc., and they are in the res / drawable folder.

Then you can use the following code to randomly set the image in 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); 
+6
source

I have no example, but I can offer you an idea.

  • Create a list of images in an array
  • Create a random number from 0 to 1 less than the number of images in the folder
  • Use the random number in step 2 as an index for the array and raise the image to display.
+1
source

. ImageView, Android.

Then I would look at 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 them with things, you can arbitrarily select an image from the list of available images and display it using ImageView.

+1
source

Source: https://habr.com/ru/post/1757530/


All Articles